您的位置:首页 > 其它

remove duplicates from sorted Array

2015-12-29 21:52 267 查看
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;

     }

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: