《剑指offer》数组中重复的数字

【 声明:版权所有,转载请标明出处,请勿用于商业用途。  联系信箱:[email protected]


题目链接:http://www.nowcoder.com/practice/623a5ac0ea5b4e5f95552655361ae0a8?rp=3&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking


题目描述
在一个长度为n的数组里的所有数字都在0到n-1的范围内。 数组中某些数字是重复的,但不知道有几个数字是重复的。也不知道每个数字重复几次。请找出数组中任意一个重复的数字。 例如,如果输入长度为7的数组{2,3,1,0,2,5,3},那么对应的输出是重复的数字2或者3。

思路
我们从头到尾扫描这个数组,首先看第i位的数字x是否等于i,不等则把x与a[x]交换,然后继续这个操作直到新的x等于i
如果此时x与a[x]相等,那么这就是一个重复的值。


class Solution
{
	public:
		// Parameters:
		//        numbers:     an array of integers
		//        length:      the length of array numbers
		//        duplication: (Output) the duplicated number in the array number
		// Return value:       true if the input is valid, and there are some duplications in the array number
		//                     otherwise false
		bool duplicate(int num[], int len, int* duplication)
		{
			if(len==0)
				return false;
			for(int i = 0; i<len; i++)
			{
				while(num[i]!=i)
				{
					if(num[i]==num[num[i]])
					{
						*duplication = num[i];
						return true;
					}
					swap(num[i],num[num[i]]);
				}
			}
			return false;
		}
};


你可能感兴趣的:(剑指offer,牛客网)