美文网首页
26. Remove Duplicates from Sorte

26. Remove Duplicates from Sorte

作者: AlanGuo | 来源:发表于2017-01-06 12:06 被阅读0次

    Given a sorted array, 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 in place with constant memory.

    For example,
    Given input array 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 new length.

    Solution:

    这道题的技巧是数组已经排序了,所有的duplicated的元素都是相邻的。因此可以使用two pointers的思路,用一个i指针遍历所有元素的同时,用另一个j指针指向当前被拿来作比较的元素,如果i指向的元素等于j指向的元素,则什么都不做;如果i指向的元素不等于j指向的元素,意味着从此以后i指向的元素永远不会再与j指向的相等。因此可以将i指向的元素放在j指向元素的后一个位置并向后移动j指针(被拿来作比较的元素变成原来的后一个元素了)。

    public class Solution 
    {
        public int removeDuplicates(int[] nums) 
        {
            int j = 0;
            for(int i = 0; i < nums.length; i ++)
            {
                if(nums[j] != nums[i])
                {
                    nums[j + 1] = nums[i];
                    j ++;
                }
            }
            return j + 1;
        }
    }
    

    相关文章

      网友评论

          本文标题:26. Remove Duplicates from Sorte

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