二刷
Runtime: 1 ms, faster than 67.57% of Java online submissions for Find Minimum in Rotated Sorted Array II.
Memory Usage: 43.3 MB, less than 61.79% of Java online submissions for Find Minimum in Rotated Sorted Array II.
class Solution {
public int findMin(int[] nums) {
if (nums == null) {
throw new IllegalArgumentException();
}
int start = 0, end = nums.length - 1;
while (start + 1 < end) {
int mid = start + (end - start) / 2;
if (nums[mid] < nums[end]) {
end = mid;
} else if (nums[mid] == nums[end]) {
end--;
} else {
start = mid + 1;
}
}
return Math.min(nums[start], nums[end]);
}
}
一刷
Version #2 Better只考虑是否舍弃后半段
若mid, end 相等有可能
1.[3, 3, 3, 3, 3, 3] All sorted
2.[3, 3, 3, 1, 3, 3] Left half sorted
3.[1, 2, 3, 3, 3, 3] Right half sorted
So the only thing we can do is reduce end pointer by 1
100.00 %
class Solution {
public int findMin(int[] nums) {
if (nums == null || nums.length == 0) {
throw new IllegalArgumentException();
}
int start = 0;
int end = nums.length - 1;
while (start < end) { // [start, end]
int mid = start + (end - start) / 2;
if (nums[mid] == nums[end]) {
end--;
} else if (nums[mid] < nums[end]) {
end = mid;
} else { // nums[mid] > nums[end]
start = mid + 1;
}
}
return nums[start];
}
}
Version #1
把 start, mid, end相等作为edge case
17.04 %
class Solution {
public int findMin(int[] nums) {
// [3, 3, 3, 1, 3, 3]
// [1, 1, 1, 3, 3, 3]
if (nums == null || nums.length == 0) {
throw new IllegalArgumentException();
}
int start = 0;
int end = nums.length - 1;
while (start < end) { // [start, end]
int mid = start + (end - start) / 2;
if (nums[mid] == nums[end] && nums[start] == nums[mid]) {
start++;
end--;
} else if (nums[mid] <= nums[end]) {
end = mid;
} else { // nums[mid] > nums[end]
start = mid + 1;
}
}
return nums[start];
}
}
No comments:
Post a Comment