p153

LeetCode p153 Find Minimum in Rotated Sorted Array 题解

1.题目:

Suppose a sorted array is rotated at some pivot unknown to you beforehand.
(i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).
Find the minimum element.
You may assume no duplicate exists in the array.

题意:

输入一个有序数组,它有可能会从某处折断反转,找出数组中最小的那个数。

2.解题思路:

采用二分。。考虑边界条件。TUT

3.代码


[title] [] [url] [link text]
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
 
public class Solution {
public int findMin(int[] nums) {
int ans = nums[0];
int len = nums.length;
int left = 0;
int right = len;
int mid;
for (;;) {
mid = (left + right) / 2;
// System.out.println(mid);
if (mid - 1 < 0 || mid > len - 1)
break;
if (left > right)
break;
if (nums[mid] < nums[mid - 1]) {
ans = ans < nums[mid] ? ans : nums[mid];
break;
} else {
if (nums[mid] > nums[0]) {
left = mid + 1;
} else {
right = mid;
}
}

}
return ans;
}
}


4.一些总结: