剑指offer题8_旋转数组的最小数字
2018-01-16 19:13
423 查看
一.题目:
把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。输入一个递增排序的数组的一个旋转,输出旋转数组的最小元素。例如数组{3, 4, 5, 1, 2}为{1, 2, 3, 4, 5 }的一个旋转,该数组的最小值为1。二.分析:
1.本题给出的数组在一定程度上是排序的,因此我们可以尝试着用二分查找法的思路来寻找这个最小的元素。2.按照定义有一个特例:如果把排序数组的前面的0个元素搬到最后面,即排序数组本身,这仍然是数组的一个旋转。
3.当两个指针指向的数字及它们中间的数字三者相同的时候,我们无法判断中间的数字是位于前面的子数组还是后面的子数组中,此时我们不得不采用顺序查找的方法。
三.答案:
int min(int* numbers, int length) { if (numbers == NULL || length <= 0) { throw new std::exception("Invalid parameters"); } int index1 = 0; int index2 = length - 1; int indexMid = index1; while (numbers[index1] >= numbers[index2]) { if (index2 - index1 == 1) { indexMid = index2; break; } indexMid = (index1 + index2) / 2; if (numbers[index1] == numbers[index2] && numbers[indexMid] == numbers[index1]) { return MinInOrder(numbers, index1, index2); } if (numbers[indexMid] >= numbers[index1]) { index1 = indexMid; } else if (numbers[indexMid <= numbers[index2]]) { index2 = indexMid; } } return numbers[indexMid]; } int minInOrder(int* numbers, int index1, int index2) { int result = numbers[index1]; for (int i = index1 + 1; i < index2; i++) { if (result > numbers[i]) { result = numbers[i]; } } return result; }
四.相关题目:
1.哈希表相关:(1)剑指offer面试题35:第一个只出现一次的字符
2.二叉搜索树:
(1)剑指offer面试题24:二叉搜索树的后序遍历序列
(2)剑指offer面试题27:二叉搜索树与双向链表
相关文章推荐
- 剑指Offer----旋转数组的最小数字
- 剑指Offer面试题8旋转数组的最小数字(二分查找)附带快排和按年龄排序
- 【剑指offer】六,旋转数组中的最小数字
- 剑指offer--旋转数组的最小数字
- 剑指offer之旋转数组的最小数字
- 剑指offer(旋转数组中的最小的数字)
- 剑指offer——旋转数组最小数字问题
- 剑指offer:08 旋转数组的最小数字
- 剑指offer-面试题8:旋转数组中的最小数字
- 剑指offer-面试题8:旋转数组的最小数字
- 剑指offer 旋转数组的最小数字
- 剑指Offer-旋转数组的最小数字
- 剑指offer 旋转数组的最小数字
- [牛客网,剑指offer,python] 旋转数组的最小数字
- 剑指offer面试题[8]-旋转数组的最小数字
- 【剑指Offer】面试题8:旋转数组的最小数字
- 【剑指offer——JAVA实现】旋转数组的最小数字(含思路解答示意图)
- [九度OnlineJudge][剑指Offer]题目1386:旋转数组的最小数字
- 剑指Offer--008-旋转数组的最小数字
- 剑指offer编程题——08 旋转数组中的最小数字