leetcode26——删除数组中重复的项

给定一个排序数组,你需要在原地删除重复出现的元素,使得每个元素只出现一次,返回移除后数组的新长度。不要使用额外的数组空间,你必须在原地修改输入数组并在使用 O(1) 额外空间的条件下完成。

给定数组 nums = [1,1,2],

函数应该返回新的长度 2, 并且原数组 nums 的前两个元素被修改为 1, 2。

你不需要考虑数组中超出新长度后面的元素。

class Solution {
    public int removeDuplicates(int[] nums) {
    //思想:数组问题一般用双指针
        if(nums.length==0)
            return 0;
        if(nums.length==1)
            return 1;
        int first=0;
        int last=1;
        int count=1;
        while(last<nums.length){
            if(nums[first]==nums[last]){
                last++;
            }else{
                count++;
                first++;
                nums[first]=nums[last];
                last++;
            }
        }
        return count;
    }
}

猜你喜欢

转载自blog.csdn.net/u010651249/article/details/84349440