数组中重复的数字
长度为n且所有数字都在0~n-1范围内(包含所有0~n-1的数字),查找重复的数字.
编程分析
二分法:遍历数组在(0~[n/2])中元素的个数num,若num>[n/2]+1继续二分,直到找到重复出现的数字。
代码
// LeetXodeTest.cpp : 定义控制台应用程序的入口点。
#include "stdafx.h"
#include <iostream>
#include <vector>
#include<array>
#include<memory>
#include<string>
#include < unordered_map >
#include "mathClass.h"
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 = ((end - start) >> 1) + start;//差值右移一位(除2向左取整)加上起始位置为中间位置
int count = countRange(numbers, length, start, middle);
if (end == start)
{
if (count > 1)
return start;
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);
for (int i = 0; i < dupLength; ++i)
{
if (result == duplications[i])
{
std::cout << testName << " passed." << std::endl;
return;
}
}
std::cout << testName << " FAILED." << std::endl;
}
// 多个重复的数字
void test1()
{
int numbers[] = { 2, 3, 5, 4, 3, 2, 6, 7 };
int duplications[] = { 2, 3 };
test("test1", numbers, sizeof(numbers) / sizeof(int), duplications, sizeof(duplications) / sizeof(int));
}
void main()
{
test1();
system("PAUSE");
}