Remove Duplicates from Sorted Array

Description:

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.

限定条件:

不要重新开辟一个新数组空间,在原地操作

问题描述:

给一个已经排好序的数组,删除里面的重复元素,保证最后数组中每个元素只出现一次,最后返回处理过数组的长度。

解法一:

思路:

在Java语言中,所有的非原始数据类型(int double char boolean)都是对象,例如数组和字符串也是对象。另外数组支持迭代,所以可以用foreach语句迭代每个元素。在循环体中只有当前元素大于前一个元素,那么才把当前迭代值赋给数组对应位置,并且将索引i加1。循环结束后,返回索引值i,也就是处理过的数组的长度。

Code:

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;
    }
}
trick:

这里的||运算符有短路求值(short circuit evaluation)特点 ,第一个condition为真,后面的condition就不做了,直接进入循环,所以不会有nums[-1]的情况

解法二:

思路:

去掉了i ==0 情况 ,看的还不太明白,大致的意思是第一个元素不会改变

Code:

public int removeDuplicates(int[] nums) {
    int i = nums.length > 0 ? 1 : 0;
    for (int n : nums)
        if (n > nums[i-1])
            nums[i++] = n;
    return i;
}

解法三:

哈希表

public class Solution {
    /**
     * @param nums an array of integers
     * @return the number of unique integers
     */
    public int deduplication(int[] nums) {
        // Write your code here
        if (nums == null || nums.length == 0){
            return 0;
        }
        HashSet<Integer> set = new HashSet<>();

        for (int i = 0; i < nums.length; i++){
            set.add(nums[i]);
        }

        int index = 0;
        for (int num : set){
            nums[index++] = num;
        }
        return set.size();
        }
    }

解法四

同向双指针,注意先自增len…

public class Solution {
    public int removeDuplicates(int[] nums) {
        if (nums == null || nums.length == 0){
            return 0;
        }
        int len = 0;
        for (int i = 0; i < nums.length; i++){
            if (nums[i] != nums[len]){
                nums[++len] = nums[i];
            }
        }
        return len + 1;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值