leetcode每日一题-26:删除有序数组中的重复项

leetcode每日一题-26:删除有序数组中的重复项

链接

删除有序数组中的重复项



题目

在这里插入图片描述



分析

这是实现一个简单的去重操作,需要掌握,首先我们从0开始,然后每次找到不重复的元素加入其中,因为数组是有序的,只需要从前往后遍历即可.



代码

C++

class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
        // 数组去重后的存储位
        int idx = 0;
        for(int i= 0 ; i<nums.size() ; )
        {
            // 把不重复的元素加入其中
            nums[idx++] = nums[i];
            // 把和当前元素重复的都去掉,找到下一个不重复的元素
            int j = i + 1;
            while(j <nums.size() and nums[j] == nums[i]) j++;
            i = j;
        }

        // 返回去重后的数组长度
        return idx;
    }
};

java

class Solution {
    
    
    public int removeDuplicates(int[] nums) {
    
    
        int n = nums.length;
        if (n == 0) {
    
    
            return 0;
        }
        int fast = 1, slow = 1;
        while (fast < n) {
    
    
            if (nums[fast] != nums[fast - 1]) {
    
    
                nums[slow] = nums[fast];
                ++slow;
            }
            ++fast;
        }
        return slow;
    }
}

作者:LeetCode-Solution

Guess you like

Origin blog.csdn.net/qq_45826803/article/details/121175655