`
淡淡的一抹
  • 浏览: 19315 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

Remove Duplicates from Sorted Array

 
阅读更多
题目描述
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.

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

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

解题思路
将数组中多余的元素删去,难点在于不使用额外的空间,这时就需要用到重复元素的数目这个变量。

自己的代码
package leetcode;

import java.util.Arrays;

public class RemoveDuplicatesFromSortedArray {
	public int removeDuplicates(int[] A) {
		int sum = 0;
		if(A.length > 1){
			for(int i = 1; i < A.length; i++){
				if(A[i] == A[i-1]) sum++;
				else A[i-sum] = A[i];
			}
		}
        return A.length - sum;
    }
	
	public static void main(String[] args) {
		int[] A = {1, 2, 2, 2, 3, 3, 4};
		
		RemoveDuplicatesFromSortedArray rdfsa = new RemoveDuplicatesFromSortedArray();
		System.out.println(rdfsa.removeDuplicates(A));
		System.out.println(Arrays.toString(A));
	}
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics