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

leetcode-26 Remove Duplicates from Sorted Array

时间:2015-04-29 17:09:23      阅读:116      评论:0      收藏:0      [点我收藏+]

标签:



问题描述:

Givena sorted array, remove the duplicates in place such that each element appearonly once and return the new length.

Do not allocate extra space for another array, youmust do this in place with constant memory.

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

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

问题分析:使用一个count统计不同的元素个数,然后注意A[count] = A[i]来消除重复元素即可

代码:

public class Solution {
    public int removeDuplicates(int[] A) {
        if(A == null || A.length == 0)
			return 0;
		int count = 1;		
		for(int i = 1; i < A.length; i++)
		{
			if(A[i] != A[i - 1])
			{
				//更新A[count]
				A[count] = A[i];
			    //更新count
				count ++;
			}
		}
		return count;
    }
}

leetcode-26 Remove Duplicates from Sorted Array

标签:

原文地址:http://blog.csdn.net/woliuyunyicai/article/details/45368167

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