《剑指offer》面试题3:题目二

不修改数组的条件下,找出数组中重复的数字;其中数组长度为n+1,数组值的范围1~n;

思路:利用二分的思想,将数组值1~n分割为1~middle的n1,middle+1~n的n2; 从头开始遍历一遍数组,统计在1~middle范围内数组中值的个数count,如果count>middle,那么重复的数字就在该数组中(n1),否者在n2;直到end = start,找到重复的。时间复杂度为O(nlogn);

1.判断在1~middle中重复的数值有多少;

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

2.由count的数值可以得到重复的数组在n1还是n2;如果end = start 说明找到了最后一个元素

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

	int start = 1;
	int end = length - 1;
	while (end >= start)
	{
		int middle = start + ((end - start) >> 1);
		int count = getCountRange(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;
}

点赞