首页 > 技术文章 > [leetcode] Remove Duplicates from Sorted Array

moonfighting 2015-01-21 00:01 原文

题意:

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].

 

给定一个有序数组,删除数组中成对出现的数,保证数组中每个数只出现一次,返回最终的数组长度。

这题需要注意的地方是不仅要检测返回的数组长度,同时也要检查返回的数组内容。

思路是设定两个下标,一个i遍历整个数组,一个index记录当前需要比较的数,同时也是返回数组的长度,在遍历的过程中如果遇到A[i]不等于A[index],就将A[i]插入到A[index]后面,具体实现代码如下:

int removeDuplicates(int A[], int n) {
        if(n == 0)
            return 0;
        int index = 0;
	for(int i = 1; i < n; i++)
	{	
	  if(A[i] != A[index])
	  {
		  A[++index] = A[i];    //当A[i] 不等于 当前index的值时,将A[i] 插入到index后面
	  }
	}
	return index + 1;
    }

  

推荐阅读