学习笔记3——不修改数组找出重复的数字(空间复杂度为O(1))

在一个长度为n+1的数组里的所有数字都在1~n的范围内。所以数组中至少有一个数字是重复的。请找出数组中任意一个重复的数字,但不能修改输入的数组。例如,如果输入长度为8的数组{2,3,5,4,3,2,6,7},那么对应的输出是重复的数字2或者3。

具体代码如下:

#include <iostream>

using namespace std;

int countRange(const int *numbers, int length, int start, int end);

int getDuplication(const int* numbers, int length){
	if(numbers == nullptr || length <= 0)
		return -1;

	int start = 1;
	int end = length - 1;
	
	while(end >= start){
		int middle = (start + end) / 2;
		//cout << "***** " << middle << " *****" << endl;
		int count = countRange(numbers, length, start, middle);
		if(end == start){
			if(count > 1)
				return start; //重复数字为1
			else
				break;
		}
		if(count > (middle - start + 1))
			end = middle;
		else
			start = middle + 1;
	}
	return -1;
}

int countRange(const int *numbers, int length, int start, int end){
	if(numbers == nullptr)
		return 0; 

	int count = 0;
	for (int i = 0; i < length; i++){
		if(numbers[i] >= start && numbers[i] <= end)
			count++;
	}
	return count;
}

void test(const char* testName, int* numbers, int length, int* duplications, int dupLength){
	 int result = getDuplication(numbers, length);
	 //cout << "----- " << result << " -----" << endl;
	 for(int i = 0; i < dupLength; i++){
		 if(result == duplications[i]){
			 cout << testName << " Passed." << endl;
			 return;
		 }
	 }
	 cout << testName << "Failed." << endl;
}

//测试用例 -> 数组中存在多个重复的数字
void MyTest(){
	int numbers[] = { 1, 2, 2, 6, 4, 5, 6 };
	int duplications[] = { 2, 6 };
	test("MyTest", numbers, sizeof(numbers) / sizeof(int), duplications, sizeof(duplications) / sizeof(int));
}

int main(){
	MyTest();
	return 0;
}

**- 优点:采用二分查找的思路,如果输入长度为n的数组,那么函数countRange将被调用O(logn)次,每次需要O(n)的时间,因此总的时间复杂度是O(nlogn),每次需要O(n)的时间,因此总的时间复杂度是O(n),空间复杂度为O(1)。

  • 缺点:这种算法不能保证找出所有重复的数字。例如,该算法不能找出数组{2,3,5,4,3,2,6,7}中重复的数字2。**
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值