leetcode 虐我篇之(五)Remove Duplicates from Sorted Array

    昨天晚上被Remove Duplicates from Sorted List 虐惨了。因为链表东西不熟悉。今天我就找了一题类似的,但是这次操作的是数组。题目是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].
    这个题目跟上次那个链表去重的意思完全一样,只是返回类型要返回数组元素个数。题目还有另外的要求是不能够申请另外的数组,必须是要常量内存处理。就是说不能够先用另外一个数组存储没有重复的值,再返回。由于有了链表的题目基础,对这题我也是直接一个遍历,中间判断一下是否相等,如果不等,就把前一个值移动到数组前面去替换原来的值。这样就能够保证前面的数是不重复的,这里定义了一个计数器num,替换的位置就在下标为num的位置。循环结束后,最后一个数也要做相应处理。最后不要忘了数组为空的情况,还有当数组是一个情况,就不用考虑了,直接返回1即可。

    代码如下:

int removeDuplicates(int A[], int n) 
{
	if (1>= n)
	{
		return n;
	}

	int num = 0;
	int i = 0;

	//判断大于等于2个的情况
	for (;i < n-1; i++)
	{
		if (A[i] == A[i+1])
		{
			//null
		}
		else
		{
			//如果不等,则将前一个移到前面去
			A[num] = A[i];
			num++;	
		}
	}
	
	//最后一个位置要加上去
	A[num] = A[i];	

	return num+1;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章