leetcode [26] Remove Duplicates from Sorted Array

Insert picture description here

Title address

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

Ideas

This question is the solution of O (n). If you fight for speed, it means pruning.
Note that in the question: you do n’t need to consider the elements behind the new length in the array. Description is to operate on the original array

solution

class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
        if (nums.empty()) return 0; // 别忘记空数组的判断
        int index = 0;
        for (int i = 0; i < (nums.size() - 1); i++){
            if(nums[i] != nums[i + 1]) { // 一旦发现和前一个不相同,就把num[i+1] 赋值给 nums[++index]
                nums[++index] = nums[i + 1]; // index = 0 的数据一定是不重复的,所以直接 ++index
            }
        }
        return index + 1; //别忘了index是从0开始的,所以返回index + 1
    }
};

I am a code junior. I have been engaged in technical research and development at BAT for many years. I use my spare time to repaint leetcode. For more original articles, please pay attention to "Code Random Notes".

Published 236 original articles · praised 251 · 270,000 views +

Guess you like

Origin blog.csdn.net/youngyangyang04/article/details/105347305