天天看點

《劍指offer》面試題3:數組中的重複的數字

題目一:找出數組中重複的數字

書上的解法:

bool duplicate(int numbers[],int length,int* duplication)
{
	if(numbers==nullptr || length<=0)
		return false;
	for(int i=0;i<length;++i)
	{
		if(numbers[i]<0 || numbers[i]>length-1)
			return false;
	}

	for(int i=0;i<length;++i)
	{
		while(numbers[i]!=i)
		{
			if(numbers[i]==numbers[numbers[i]])
			{
				*duplication=numbers[i];
				return true;
			}

			//swap numbers[i] and numbers[numbers[i]]
			int temp=numbers[i];
			numbers[i]=numbers[temp];
			numbers[temp]=temp;
		}
	}

	return false;
}
           

在上述代碼中,找到的重複數字通過參數duplication 傳給函數的調用者,而函數的傳回值表示數組中是否有重複的數字。當輸入的數組中存在重複的數字時,傳回true;否則傳回false。

測試用例:

a.長度為n 的數組裡包含一個或多個重複的數字。

b.數組中不包含重複的數字。

c.無效輸入測試用例(輸入空指針:長度為n 的數組中包含0~n-1 之外的數字)

繼續閱讀