Algorithm deliberate practice by deleting duplicates -LeetCode combat 02- sorted array

Title: Delete duplicate entries sorted array

Topic link: https: //leetcode-cn.com/problems/remove-duplicates-from-sorted-array/
see this question, the first reaction is to direct violence:

class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
        int len = nums.size();
        for(int i = 1; i < len; i++)
        {
            for(int j = 0; j < i; j++)
            {
                if(nums[j] == nums[i])
                {
                    int k = i;
                    while(k < len - 1)
                    {
                        nums[k] = nums[k + 1];
                        k++; 
                    }
                    len--;
                    i--;
                    break;
                }
            }
        }
        return len;
    }
};

Here Insert Picture Description
Although can be solved, but the speed is appalling.
After reading the official answer, I feel really very clever, speed really improved a lot:

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

Here Insert Picture Description
Write when it ignores the input array is empty.
The road is long Come, happiness and earth!

Published 16 original articles · won praise 0 · Views 287

Guess you like

Origin blog.csdn.net/DZZ18803835618/article/details/104607900