标签:
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]
.
同一数组,去重,并且保持线性空间。
都说这道题不难,但是这道题却总是做不对,最开始用了双重循环,时间超时了
后来看了人家的答案,用两个指针,一个指向被比较的当前元素,一个指向要去比较的后面的数,如果后面的数和这个数相等,则该指针往后推,直道找到不同的数,则把这个数挪过来,之后继续比较,把后面的数均挪过来。
1 package Remove.Duplicates.from.Sorted.Array; 2 3 public class RemoveDuplicatesfromSortedArray1 { 4 public int removeDuplicates(int[] A) { 5 int len=A.length; 6 if(len<=1) return len; 7 int first=0; 8 int second=1; 9 while(second<len){ 10 if(A[first]==A[second]){ 11 second++; 12 }else{ 13 first++; 14 A[first]=A[second]; 15 second++; 16 } 17 18 } 19 return first+1; 20 } 21 public static void main(String args[]){ 22 RemoveDuplicatesfromSortedArray1 service=new RemoveDuplicatesfromSortedArray1(); 23 int []A={1,1,1,1,2,3,3}; 24 int a=service.removeDuplicates(A); 25 26 System.out.println(a); 27 28 } 29 }
Leetcode Remove Duplicates from Sorted Array
标签:
原文地址:http://www.cnblogs.com/criseRabbit/p/4237379.html