LeetCode Problem -- 26. Remove Duplicates from Sorted Array

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/m0_38088298/article/details/85759434
  • 描述:
    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]);
}

  • 分析:此题给出一个已经排序好的数组,要求实现一个函数返回数组中不同元素的个数,限定空间复杂度为O(1),也就是不能使用辅助数组,同时由于题中给出的是数组的引用,因此还需实现将不同元素都移动到数组前n个位置上。
  • 思路一:用一个int值记录每次需要替换的位置(slow),同时对数组中的元素前后两两比较,如果前后两个不同则将后一个元素替换到slow记录的位置。
class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
        int slow = 0, flag = 1;
        if (nums.empty()) return 0;
        for (int i = 0; i < nums.size() - 1; i++) {
            if (nums[i + 1] != nums[i]) {
                nums[++slow] = nums[i + 1];
                flag++;
            }
        }
        return flag;
    }
};
  • 思路二:双指针法,和思路一的想法类似,只是在遍历时从i = 1开始。
class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
        int slow = 0;
        if (nums.empty()) return 0;
        for (int i = 1; i < nums.size(); i++) {
            if (nums[i] != nums[slow]) {
                nums[++slow] = nums[i];
            }
        }
        return slow + 1;
    }
};

猜你喜欢

转载自blog.csdn.net/m0_38088298/article/details/85759434