#100 Remove Duplicates from Sorted Array

来源:互联网 发布:数组指针和指针数组 编辑:程序博客网 时间:2024/05/16 10:00

题目描述:

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.

Example

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

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

题目思路:

这题还是用two pointers,一个i去遍历,一个idx守在原地。如果A[i] == A[idx],就不取A[i];否则,A[idx + 1] = A[i]。

Mycode(AC = 42ms):

class Solution {public:    /**     * @param A: a list of integers     * @return : return an integer     */    int removeDuplicates(vector<int> &nums) {        // write your code here        if (nums.size() <= 1) return nums.size();                int idx = 0;        for (int i = 1; i < nums.size(); i++) {            if (nums[i] != nums[idx]) {                nums[idx + 1] = nums[i];                idx++;            }        }                return idx + 1;    }};


0 0
原创粉丝点击