LeetCode 26. Delete duplicates in sorted array (C ++)

Problem:
Given a sorted array, you need to delete the repeated elements in place, so that each element appears only once, and return the new length of the array after removal.
Don't use extra array space, you must modify the input array in place and do it with O (1) extra space.

Example 1:

Given the array nums = [1,1,2], the
function should return a new length of 2, and the first two elements of the original array nums are modified to 1, 2.
You don't need to consider the elements in the array beyond the new length.

Example 2:

Given nums = [0,0,1,1,1,2,2,3,3,4], the
function should return a new length of 5, and the first five elements of the original array nums are modified to 0, 1, 2, 3, 4.
You don't need to consider the elements in the array beyond the new length.

Explanation:
Why the returned value is an integer, but the answer to the output is an array?
Please note that the input array is passed by "reference", which means that modifying the input array in the function is visible to the caller.
You can imagine the internal operation as follows:

// nums is passed by "reference". In other words, do not make any copies of the actual parameters
int len ​​= removeDuplicates (nums);
// Modify the input array in the function is visible to the caller.
// Based on the length returned by your function, it will print out all the elements in the length range in the array.
for (int i = 0; i <len; i ++) {
print (nums [i]);
}

Problem-solving ideas: I
just thought about iterating through the array. Use a subscript index as a marker, and then judge whether the current number and the number of the marked subscript are equal when traversing the array. If they are not equal, the subscript index is incremented and assigned to it.
However, it was not resolved, and then the erase method was used. The code is as follows:

class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
        int index=0;
        for(auto it=nums.begin()+1;it<nums.end();it++,index++){
            if(*it == nums[index]){
                nums.erase(it);
                it--;
                index--;
            }
        }
        return nums.size();
    }
};

Later, I felt that using the erase method was too time-consuming, so I continued to think about the method of traversal and assignment. After the solution, the time consumption is significantly reduced. The AC code is as follows:

class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
        if(0 == nums.size()) return 0; //注意长度为0的情况
        int index=0;
        for(int i=1;i<nums.size();i++){
            if(nums[i] != nums[index]){
                index++;
                nums[index] = nums[i];
            }
        }
        return index+1;
    }
};
Published 111 original articles · won praise 2 · Views 3533

Guess you like

Origin blog.csdn.net/m0_38088647/article/details/101715811