154. Find Minimum in Rotated Sorted Array II
アプローチ
1. 二分探索
class Solution {
public int findMin(int[] nums) {
if (nums == null || nums.length == 0) {
return 0;
}
int start = 0;
int end = nums.length - 1;
if (nums[start] < nums[end]) {
return nums[start];
}
while (start < end) {// not putting <= because the array contains unique elements
int mid = start + (end - start) / 2;
if (nums[mid] < nums[end]) {
end = mid;
// end を利用
} else if ( nums[mid] > nums[end] ) {
// right side is rotated, expecting smallest number between mid + 1 <= end;
// 5 6 7 8 9 1 2 3
start = mid + 1;
} else {
// reduce duplicate
// 5 6 7 8 9 1 1 3
end--;
}
}
return nums[end];
}
}
2. ソート
class Solution {
public int findMin(int[] nums) {
Arrays.sort(nums);
return nums[0];
}
}
3. 全体探索
class Solution {
public int findMin(int[] nums) {
int min = Integer.MAX_VALUE;
for (int num : nums) {
if (num < min)
min = num;
}
return min;
}
}