26. Remove Duplicates from Sorted Array[E]删除排序数组中的重复项

题目


Given a sorted array nums, 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 1:
 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 returned length.
Example 2:
 Given nums = [0,0,1,1,1,2,2,3,3,4],
 Your function should return length = 5, with the first five elements of nums being modified to 0, 1, 2, 3, and 4 respectively.
 It doesn't matter what values are set beyond the returned length.
Clarification:
Confused why the returned value is an integer but your answer is an array?
Note that the input array is passed in by reference, which means modification to the input array will be known to the caller as well. Internally you can think of this:

// nums is passed in by reference. (i.e., without making a copy) 
int len = removeDuplicates(nums); 
// any modification to nums in your function would be known by the caller. 
// using the length returned by your function, it prints the first len elements.
for (int i = 0; i < len; i++) { 
    print(nums[i]); 
}

思路


双指针法

本题要返回一个有序数组内不重复元素的个数,要比较数组内两个元素是否相同,需要两个下标记录,于是想到双指针法。这里要注意两点:一是函数的形参是传引用,改变形参也会改变原本的数据;二是题目要求不得声明额外的空间。
对于一个有序数组,由于不能使用额外的空间保存删除重复元素后的数组,于是想到不删除重复元素,而是替换重复元素,将重复元素替换到后面,使用两个指针:

  • pBegin:记录不重复数组的最后一个元素的下标。
    • 遇到不重复元素时,pBegin加1,表示多了一个不重复元素。
  • pEnd:用于循环。
    • 当遇到重复元素时,pEnd加1
    • 当遇到不重复元素时,先pBegin加1,此时pBegin指向的还是重复元素,pEnd指向不重复元素。将pBegin所指元素与pEnd所指元素替换,此时pBegin指向不重复元素,并且下标代表不重复数组的最后一个下标;pEnd指向重复元素。

C++

class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
        
       if(nums.size() == 0)
           return 0;
        
        int pBegin = 0;
        int pEnd = 1; 
       
        while(pEnd < nums.size()){
             if(nums[pEnd] != nums[pBegin]){
                pBegin ++;
                nums[pBegin] = nums[pEnd];
            }
            pEnd ++;
        }
        return pBegin + 1;   //从0计数的,因此长度+1
    }
};

Python

原文地址:https://www.cnblogs.com/Jessey-Ge/p/10993545.html