[LeetCode]Remove Duplicates from Sorted Array

题目描述:(https://leetcode.com/problems/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.

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

Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively. It doesn't matter what you leave beyond the new length.

标签:数组, 两个指针

解题思路:

利用两个指针,首先这两个指针i和j分别指向第0个和第1个数组元素,如果nums[i] == nums[j], 则j++, 否则将num[j]赋值给nums[++i],最后返回i + 1, 就是数组的新长度。

class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
        if (nums.size() == 0) {
            return 0;
        }
        
        int i = 0;
        int j = i + 1;
        for (; j < nums.size(); j++) {
            if (nums[i] != nums[j]) {
                nums[++i] = nums[j];
            }
        }
        return i + 1;
    }
};