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]
.
public class Solution { public int removeDuplicates(int[] A) { if (A.length==0) return 0; int length =A.length; int[] B=new int[length]; int index=0;//B指向下一个位数 int temp=0;//B已经赋值的位置 for(int i=0;i<length;i++){ //如果第一项是零的情况{0,0,2} if(A[i]==0 && index==0){ B[index]=0; index+=1; } if(A[i]!=B[temp]){ B[index]=A[i]; temp=index; index+=1; } } //给A赋值 for(int k=0;k<index;k++){ A[k]=B[k]; } return index; } }
/********************************
* 本文来自博客 “李博Garvin“
* 转载请标明出处:http://blog.csdn.net/buptgshengod
******************************************/
【LeetCode从零单排】No26.Remove Duplicates from Sorted Array
原文地址:http://blog.csdn.net/buptgshengod/article/details/43700757