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;
}


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