当前位置:网站首页>LeetCode —— 26. Remove duplicates from an ordered array

LeetCode —— 26. Remove duplicates from an ordered array

2022-06-12 22:34:00 Listen to the sea

subject

To give you one Ascending order Array of nums , Would you please In situ Delete duplicate elements , Make each element Only once , Returns the new length of the deleted array . Elemental Relative order It should be maintained Agreement .

Example

 Input :nums = [0,0,1,1,1,2,2,3,3,4]
 Output :5, nums = [0,1,2,3,4]
 explain : Function should return the new length  5 ,  And the original array  nums  The first five elements of are modified to  0, 1, 2, 3, 4 . You don't need to think about the elements in the array that follow the new length .

Ideas

Double pointer algorithm . First a pointer points to the first position , The second pointer starts from the next pointer , The number pointed to is compared with the number pointed to by the pointer , If equal , No operation , Continue to traverse ; If not equal , Move the pointer back and assign the unequal number to the number pointed to by the current pointer . And so on .

Code

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

版权声明
本文为[Listen to the sea]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202281140456264.html