题目
剑指 Offer 11. 旋转数组的最小数字
题解
双指针+二分查找
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
| class Solution { public int minArray(int[] numbers) { int left = 0; int right = numbers.length - 1;
while (left < right) { int mid = (left + right) / 2; if (numbers[mid] > numbers[right]) { left = mid + 1; } else if (numbers[mid] < numbers[right]) { right = mid; } else { return findMin(numbers,left,right); } } return numbers[left]; } public int findMin(int[] numbers,int left,int right) { int result = numbers[left]; for (int i = left;i <= right;i++) { if (numbers[i] < result) { result = numbers[i]; } } return result; } }
|
leetcode-cn
执行:
1 2
| 执行用时:0 ms, 在所有 Java 提交中击败了100.00%的用户 内存消耗:40.9 MB, 在所有 Java 提交中击败了81.71%的用户
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
| func minArray(numbers []int) int { left := 0 right := len(numbers) - 1 for left < right { mid := (left + right) / 2 if numbers[mid] > numbers[right] { left = mid + 1 } else if numbers[mid] <numbers[right] { right = mid } else { return findMin(numbers,left,right) } } return numbers[left] }
func findMin(numbers []int,left,right int) int { result := numbers[left] for i := left;i <= right;i++ { if numbers[i] < result { result = numbers[i] } } return result }
|
如果本篇文章对你有帮助,可以给作者加个鸡腿~(*^__^*),感谢鼓励与支持!
微信支付
支付宝