剑指offer 面试题3_1 数组中重复的数字

问题:找到数组中第一个重复的数字。

输入:数组,数组的长度

输出:是否存在重复的数字,如存在,则输出第一个重复的数字。

思路:如果对数组进行排序,则需要O(nlogn)的时间复杂度。因为数字在0~n-1内,每个数字都应该在其该在的位置上,如果出现重复数字,则一个位置上有多个数字,这里采用了更为效率的算法。

  • 首先,遍历整个数组,判断对该下标i是否等于数字num,
  • 如果相等,则遍历至下一个数字.
  • 如果不相等,则将该数字与下标为num进行比较。

如果相等,则找到了第一个重复的数字

如果不相等,就将两个数字进行交换,继续判断该下标i是否等于数字num'

  • 最后,如果遍历完整个数组,没有出现相等的两个数字,则得出不存在重复数字的结论。

代码:

#include <iostream>
using namespace std;
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;
		    }
		    int temp= numbers[i];
		    numbers[i] = numbers[temp];
		    numbers[temp] = temp;
		}
	}
	return false;
}
int main()
{
	int numbers[]={1,0,2,4,2};
	int duplication;
	if(duplicate(numbers, 5, &duplication))
	{
		cout<<duplication<<endl;
	}
	else
	{
		cout<<"false"<<endl;
	}
	// cin.get();
	return 0;
}

复杂度分析:时间复杂度为O(n),不需要开辟新的空间,因此,空间复杂度为O(1)。

发布了56 篇原创文章 · 获赞 10 · 访问量 6809

猜你喜欢

转载自blog.csdn.net/qq_22148493/article/details/104211003