美文网首页
Remove Duplicates from Sorted Ar

Remove Duplicates from Sorted Ar

作者: 小明今晚加班 | 来源:发表于2019-02-19 20:29 被阅读0次
    题目描述:

    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.

    Example 1:

    Given nums = [1,1,2],

    Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively.

    It doesn't matter what you leave beyond the returned length.

    Example 2:

    Given nums = [0,0,1,1,1,2,2,3,3,4],

    Your function should return length = 5, with the first five elements of nums being modified to 0, 1, 2, 3, and 4 respectively.

    It doesn't matter what values are set beyond the returned length.

    分析:题目给出一个有序的数组,在不申请额外空间的条件下,删除重复元素。这就断了我们使用List或者Set的念头。另外数组有序也很重要。解决问题的思路:假设有个游标,刚开始指向数组头部,当发现后一个数与前一个数不相等时,让游标向前移动一步,以此类推。说是这么说,但是在代码中体现的就是如果有后一个数与前一个数相等时,直接将其略过,直到后面有不与之相等的数覆盖掉前面的数。
    class Solution {
        public int removeDuplicates(int[] nums) {
           if (nums.length == 0) {
                return 0;
            }
            int len = 1;
            for (int i = 1; i < nums.length; i++) {
                if (nums[i] != nums[i - 1]) {
                    if (nums[i] != nums[len]) {
                        nums[len] = nums[i];
                    }
                    len++;
                }
            }
            return len;
        }
    }
    

    相关文章

      网友评论

          本文标题:Remove Duplicates from Sorted Ar

          本文链接:https://www.haomeiwen.com/subject/hrxqyqtx.html