《剑指offer》面试题3(一) 数组中重复的数字

本文介绍了三种查找数组中重复数字的方法:交换查找、哈希查找及排序查找,并详细解析了每种方法的具体实现过程与时间、空间复杂度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

--------------------------------------------------------------------------------------------------------------------------------------------------------------------------

1> 交换查找

步骤: 重排数组:

复杂度:

  •    扫描每个数字
  •    数字m = 下标i      继续扫描
  •    数字m ≠ 下标i     
  •           下标i数 = 下标m数      重复
  •           下标i数 ≠ 下标m数      交换

       数组排序中尽管两重循环,每个数字最多交换两次就可以找到位置,时间复杂度为O(n)

       操作在输入数组,不需额外分哦欸内存,空间复杂度O(1)

  

 

#include<cstdio>
#include<iostream>

using namespace std;

bool duplicate(int numbers[], int length, int* duplication)
{
	// 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
	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];

				cout << *duplication << endl;
				return true;
			}

			//交换numbers[i]和number[numbers[i]]
			int temp = numbers[i];
			numbers[i] = numbers[temp];
			numbers[temp] = temp;
		}
	}
	return false;
}

void main()
{
	int numbers[] = { 2, 1, 3, 5, 4 };
	int len = sizeof(numbers) / sizeof(int);
	int duplication;
	duplicate(numbers, len, &duplication);
	
}

 

 

2>哈希查找

     从头到尾扫描数组,每扫描到一个数字,判断该数字是否在哈希表中,如果该哈希表还没有这个数字,那么加入哈希表,如果已经存在,则返回该重复的数字;

        算法时间复杂度:O(n),空间复杂度:O(n)。

        unordered_map的内部实现方式为哈希表。

#include <iostream>
#include "stdlib.h"
#include <unordered_map>

using namespace std;

int main()

{
	int numbers[] = { 2, 3, 1, 0, 2, 5, 3 };
	int len = sizeof(numbers) / sizeof(numbers[0]);
	int flag = 0;//是否找到重复数字的标志位

	std::unordered_map<int, int> hashmap = {};

	for (int i = 0; i < len; i++)
	{
		if (hashmap.empty())//判断哈希表是否为空
		{
			hashmap.insert({ numbers[i], numbers[i] });
		}
		else
		{
			for (auto num : hashmap) {  //遍历哈希表
				if (num.first == numbers[i])
				{
					std::cout << "重复数字:" << numbers[i] << endl;
					flag = 1;
					break;
				}
			}
			if (flag == 1)
				break;
			else
				hashmap.insert({ numbers[i], numbers[i] });
		}
	}
	system("pause");
	return 0;
}

 

3> 排序查找
   a 把输入数组排序 O(nlogn)
   b 遍历排序数组

   排序算法时间复杂度:O(nlogn),空间复杂度:O(1)。
  stl库的sort()函数具体实现结合了快速排序,插入排序和堆排序。

 


#include<iostream>
#include<vector>
#include<algorithm> //sort

using namespace std;

int main()
{
	int inputnumer[100];
	vector<int> number;
	int n;
	cout << "输入n"<<endl;
	cin >> n;
	cout << "输入数组" << endl;
	for (int i = 0; i < n; ++i)
	{
		cin >> inputnumer[i];
		number.push_back(inputnumer[i]);
	}
	
	std::sort(number.begin(),number.end());

	for (std::vector<int>::iterator it = number.begin(); it != number.end(); ++it)

	{   //迭代器相对容器起始位置的偏移即相当于数组的下标

		if ((it - number.begin()) != *it)  //减起始数字不等于下标表示有重复
		{
			std::cout << "重复数字:" << *it << endl;
		 	break;
		}
	}
	system("pause");

	//for (auto i:number) //输出vector的元素
	//	cout <<i<< endl;
	return 0;
}

 

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值