LeetCode 第二十六题(Remove Duplicates from Sorted Array) java

原题: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.

遍历一遍,去除数组中重复元素,要求不开辟新的空间。

参考了这个博客之中的解法:http://blog.csdn.net/lilong_dream/article/details/19757047 在此表示感谢。

思路:不开辟新的空间,应该是在原数组上做修改,想法是将原数组重复元素由不重复的元素替代。

1.设置两个变量,一个用于记录当前元素的位置,同事也是已经处理过的数组的长度。另一个变量用于遍历数组。

2.找到第一个与当前位置元素不相等的元素,他们之间的区域都是重复元素,可以用非重复元素替换掉。

代码:

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值