LeetCode

时间:2019-07-04
本文章向大家介绍LeetCode,主要包括LeetCode使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

数组:

1、Given an array and a value, remove all instances of that value in place and return the new length. The order of elements can be changed. It doesn't matter what you leave beyond the new length.(给定一个数组和一个值,删除该值的所有实例并返回新的长度。 元素的顺序可以改变。 你留下的新长度并不重要)

这道题很坑爹,是牛客网里的一道题,也不知道是我的理解能力差,还是它的英文写的有问题,它的测试案例很偏,不得不像下面这么做。

class Solution {
public:
    int removeElement(int A[], int n, int elem) {
        if (n == 0) return n;
        for (int i = 0; i < n; ++i){
            if (A[i] == elem)
            {
                while (n>i && A[--n] == elem);
                A[i] = A[n];
            }
        }
        return n;
    }
};

2、

Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length.

Do not allocate extra space for another array, you must do this in place with constant memory.

For example,
Given input array A =[1,1,2],

Your function should return length =2, and A is now[1,2].

给定排序数组,删除重复项,使每个元素只出现一次并返回新长度。
不要为另一个数组分配额外的空间,必须使用常量内存来执行此操作。
例如,
给定输入数组A = [1,1,2],
你的函数应该返回length = 2,A现在是[1,2]

class Solution {
public:
    int removeDuplicates(int A[], int n) {
        if(n==0) return n;
        int i=0; // 慢指针
        for(int j=1;j<n;j++) //快指针
        {
            if(A[i]!=A[j]) //如果快慢两指针指向地址内的值相同,则跳过
            {              //若不相同,则将快指针指向的值放在慢指针的后面
                A[++i] = A[j];
            }
        }
        return ++i; // 数组的长度
    }
};

原文地址:https://www.cnblogs.com/zhuifeng-mayi/p/11135018.html