remove duplicates from sorted Array

来源:互联网 发布:p身份证的软件 编辑:程序博客网 时间:2024/06/01 07:21
Given: a sorted array, 
to do: remove the duplicates in place such that each element appear only once 


and return the new length
requirment: do not allocate extra space for another array, you must do this in 


place with constant memory.


e.g. input array nums=[1,1,2]
     output 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.
26. Remove Duplicates from Sorted Array


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


another solution
public class Solution{
    public int removeDuplicates(int[] nums){
         if(nums==null || nums.length==0)
              return 0;
         Integer cur = null;//special value, means uninitialized.
         int len = 0;
         for(int n : nums){
            if(cur == null || cur < n){
                cur = n;
                nums[len++] = n;
            }
         }
         return len;
     }
}
0 0
原创粉丝点击