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.

对于排序数组,相同的值一定是聚集在一起的。
我一开始的想法是交换尾部和头部而不是覆盖,交换算法是不稳定的,这意味着我破坏了原来的有序性,从而判断一个部分是否含有一个VAL从常数时间(只要判断部分的末尾是否等于VAL)成了线性。这是一种不佳的退化。
这和remove element是不同的 前者的判断式子是O(1)(是否等于一个特定的值),而在这里,要判断是否重复在交换的情况下变成了O(N).(因为交换破坏了排序性)。

下面这张写法是和Remove Element 差不多的 说实话 我也不知道自己为啥要这样写。这张完全没有利用有序的信息,采用的是暴力搜索,O(N2),可能我当时脑子进水了。

class Solution {
    public int removeDuplicates(int[] nums) {
        if(nums==null||nums.length==0)
        return 0 ;
        if(nums.length==1)
        return 1;
        int pos1 = 1;
        int pos2 = nums.length-1;
        while(pos1<=pos2)
        {
             
            if(search(nums,nums[pos1],pos1-1))
            {
                int temp = nums[pos2];
                nums[pos2]= nums[pos1];
                nums[pos1]=temp;
                pos2--;
            }
            else
            {
                pos1++;
            }
        }
        Arrays.sort(nums,0,pos2);
        return pos2+1;
    
    }
    private boolean search (int[] nums , int target , int end)
    {
        for(int i = 0;i<=end;i++)
        {
            if(nums[i]==target)
                return true;
        }
        return false;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容