[LeetCode]26. Remove Duplicates from Sorted Array

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.


读题:

有序数组,原地操作,将重复的数值放在后面,返回无重复的数组长度

解题:

使用一个当前索引curIdx记录当前遍历到的最大的无重复数的位置,在遍历时通过将遍历索引i当前索引curIdx比较,如果不同,则将当前索引curIdx的下一位置数值替换为遍历索引i的值,并将当前索引curIdx加1

class Solution {
    public int removeDuplicates(int[] nums) {
        if (nums.length <= 1)
            return nums.length;
        int ret = 0;
        int curIdx = 0;
        int i = 1;
        while (true)
        {
            if (i >= nums.length)
                break;
            if (nums[curIdx] != nums[i])
            {
                nums[++curIdx] = nums[i]; 
            }
            i++;
        }
        return curIdx + 1;
    }
}

思题:

1.为啥要是有序数组?
因为要保证所有相同的数都在一起,有序数组的描述比较简单

猜你喜欢

转载自blog.csdn.net/weixin_43134916/article/details/82557348