二刷
写了一个bug
一开始没有包括start==end的情况,导致[1]return-1
也可以写成
if (nums[start] > nums[end]) {
return start;
}
return end;
因为保证一定有peak
class Solution {
public int findPeakElement(int[] nums) {
if (nums == null) {
return -1;
}
int start = 0, end = nums.length - 1;
while (start + 1 < end) {
int mid = start + (end - start) / 2;
if ((mid == 0 || nums[mid] > nums[mid - 1]) && nums[mid] > nums[mid + 1]) {
return mid;
}
if (nums[mid] < nums[mid + 1]) {
start = mid + 1;
} else {
end = mid;
}
}
if (start == end) {
return start;
}
if (nums[start] > nums[end]) {
return start;
}
if (nums[start] < nums[end]) {
return end;
}
return -1;
}
}
一刷
Binary Searchmid will never be nums.length - 1
100.00 %
class Solution {
public int findPeakElement(int[] nums) {
if (nums == null || nums.length == 0) {
return -1;
}
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]) // start = 0, end = 1
&& (nums[mid] > nums[mid + 1])) {
return mid;
} else if (nums[mid] > nums[mid + 1]) { // mid will never be nums.length - 1
end = mid;
} else {
// nums[mid] < nums[mid + 1]
start = mid + 1;
}
}
return start;
}
}
No comments:
Post a Comment