本文主要是介绍《剑指offer》第二版勘误,P42,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
P42,文字倒数第五行:“我们在统计数字3或者4在数组中出现的次数,它们一共出现了三次。”应该删除,因为这里并没有统计3或4的次数为三次,而是直接统计了3的次数,然后再统计了一次3的次数,得出3是重复的数字。
#include <iostream>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;
}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;int count = countRange(numbers,length,start,middle);std::cout << "start=" << start << ",end=" << end << ",middle=" << middle << ",count=" << count << std::endl;if (end == start){if (count > 1)return start;elsebreak;}if (count > (middle - start + 1)){end = middle;}elsestart = middle + 1;}return -1;
}int main()
{int a[] = {2,3,5,4,3,2,6,7};int num = getDuplication(a, 8);std::cout << "num=" << num << std::endl;return 0;
}
这篇关于《剑指offer》第二版勘误,P42的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!