Remove Duplicates from Sorted Array

题目:

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].

分析:

这题目要注意判断每一步是否超出vector的范围

解法:

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() == 0) {
            return 0;
        }
        int start = 0;
        int curr = 0;
        while (curr < nums.size() ) {
            while (nums[curr] == nums[start] && curr < nums.size() ) {
                curr++;
            }
            if (start + 1 < nums.size() && curr != nums.size() ) {
                int temp = nums[start + 1];
                nums[start + 1] = nums[curr];
                nums[curr] = temp;
                start++;
                curr++;
            }
        }
        return start + 1;
    }
};

results matching ""

    No results matching ""