码迷,mamicode.com
首页 > 其他好文 > 详细

lintcode-easy-Remove Duplicates from Sorted Array

时间:2016-03-06 08:45:55      阅读:214      评论:0      收藏:0      [点我收藏+]

标签:

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.

Given input array A = [1,1,2],

Your function should return length = 2, and A is now [1,2].

 

public class Solution {
    /**
     * @param A: a array of integers
     * @return : return an integer
     */
    public int removeDuplicates(int[] nums) {
        // write your code here
        
        if(nums == null)
            return 0;
        if(nums.length <= 1)
            return nums.length;
        
        int i = 0;
        int j = 1;
        
        while(j < nums.length){
            while(j < nums.length && nums[j] == nums[i])
                j++;
            
            if(j < nums.length){
                i++;
                nums[i] = nums[j];
            }
        }
        
        return i + 1;
    }
}

 

lintcode-easy-Remove Duplicates from Sorted Array

标签:

原文地址:http://www.cnblogs.com/goblinengineer/p/5246490.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!