26. Remove Duplicates from Sorted Array

Question

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.

思路一

题中要求不能建立新的数组,我这里使用了hashmap,又是投机取巧的做法。对数组从头到尾进行遍历,查询元素是否存在,如果不存在则把此元素存入hashmap,同时把该元素放到标记位的位置,标记位的作用是只存放不重复的元素。

代码
public class Solution {
    public int removeDuplicates(int[] nums) {
        if(nums == null || nums.length < 1)
            return 0;
        int index = 0;//将要存储未重复数字的下标
        Map<Integer,Boolean> map = new HashMap<Integer,Boolean>();
        for(int i = 0;i < nums.length;i++){
            if(!map.containsKey(nums[i])){
                map.put(nums[i],true);
                nums[index] = nums[i];
                index++;
                continue;
            }
        }
        return index;
    }
}
结果及分析

【You are here!
Your runtime beats 5.59% of javasubmissions.】这个结果真是不能接受,空间复杂度最差为O(n);

思路二

题中已经说明这是一个已经排好序的数组,也就是说后面的元素只能是越来越大或者越来越小;从头开始遍历数组,然后把第一个元素放进去,然后从第二个元素开始比较,如果相同则不存入,如果不同则存入下一位。

代码
public class Solution {
    public int removeDuplicates(int[] nums) {
        //因为这是一个已经排好序的数组,也就是说后面的元素只有可能是大于等于前面的元素或者小于等于
        int index = 0;//设置标志位,代表将要存放不重复元素的位置
        if(nums == null || nums.length < 1)
            return 0;
        for(int i = 1;i < nums.length;i++){
            if(nums[i] != nums[index]){
                index++;
                nums[index] = nums[i];
            }
        }
        return index+1;
    }
}
结果及分析

【You are here!
Your runtime beats 8.67% of javasubmissions.】感觉已经很优化了,时间复杂度为O(n),空间复杂度为O(1),可能是代码结构存在问题,不然这已经是最优的答案了。

代码优化

果然优化之后变为最优了,可惜是借鉴了别人的结果。

public class Solution {
    public int removeDuplicates(int[] nums) {
    int i = 0;
    for (int n : nums)
        if (i == 0 || n > nums[i-1])
            nums[i++] = n;
    return i;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值