Skip to content

Latest commit

 

History

History
48 lines (31 loc) · 1.21 KB

026.md

File metadata and controls

48 lines (31 loc) · 1.21 KB

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 by modifying the input array in-place with O(1) extra memory.

example:

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

思路:

题目返回的是一个长度len,使得array[0...len-1] 不重复。

设置一个int len=1指向不重复数组部分的后一位(第一个元素肯定不重复),然后从1开始遍历整个数组,如果该数和前一位相等则处理下一个,否则将该

元素赋值到len指向的位置,len++。

代码:

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