26. Remove Duplicates from Sorted Array

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;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容