[One question per day] Delete duplicate items in sorted array

https://leetcode-cn.com/problems/remove-duplicates-from-sorted-array/

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


Solution 1

Violence law, time complexity is higher!

Solution 2

Dual pointer traversal method 16ms, 7.5mb

class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
        if (nums.size() < 2) {
            return nums.size();
        }

        size_t slow = 0, fast = 1;
        while (fast < nums.size()) {
            if (nums[fast] != nums[slow]) {
                nums[++slow] = nums[fast];
            }
            fast++;
        }
        return ++slow;
    }
};

EOF

98 original articles have been published · 91 praises · 40,000+ views

Guess you like

Origin blog.csdn.net/Hanoi_ahoj/article/details/105336477