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.
public class Solution {
public int findMin(int[] nums) {
int s = 0;
int e = nums.length - 1;
if (nums[s] <= nums[e]) {
return nums[s];
}
while (s <= e) {
int m = (s + e) / 2;
if (nums[m] > nums[m + 1]) {
return nums[m + 1];
} else if (nums[m] > nums[s]) {
s = m;
} else {
e = m;
}
}
return nums[0];
}
}
======
public class Solution {
public int findMin(int[] nums) {
if (nums[0] <= nums[nums.length - 1]) {
return nums[0];
}
int start = 0;
int end = nums.length - 1;
while (start <= end) {
int mid = start + (end - start) / 2;
if (mid != 0 && nums[mid] < nums[mid - 1]) {
return nums[mid];
} else {
if (nums[mid] >= nums[0]) {
start = mid + 1;
} else {
end = mid - 1;
}
}
}
return nums[start];
}
}
==========
public class Solution {
public int findMin(int[] nums) {
int s = 0;
int e = nums.length - 1;
while (s <= e) {
int mid = s + (e - s) / 2;
if (nums[mid] < nums[e]) {
e = mid;
} else if (nums[mid] > nums[e]) {
s = mid + 1;
} else {
return nums[s];
}
}
return nums[s];
}
}
没有评论:
发表评论