每日一题6.28

问题:

Given a sorted array nums, remove the duplicates in-place such that each element appear only once and return the new length.

Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.

与上一个问题类似,只不过这里给定的是排好序的数组,同时要求修改为删除重复的元素。

思路:设置好标志位i,同时因为是排好序的数组,所以我们可以利用元素之间的大小不同这一特性去遍历。

class Solution {
    public int removeDuplicates(int[] nums) {//注意不仅仅需要返回长度,还要保留好数组。
        if(nums.length==0)
            return 0;
        int i=0;
        for(int n:nums)
        {
            if(i==0||n>nums[i-1])
                nums[i++]=n;
        }
        return i;
    }
}


猜你喜欢

转载自blog.csdn.net/q_all_is_well/article/details/80871269