Search in Rotated sorted Array
中间值大于起始值,且起始值大于终止值
public int findMin(int[] num) {
int l = 0;
int r = num.length - 1;
int min = num[0];
while (l < r) {
int m = (l+r)/2;
if (num[l] < num[m]) {
min = Math.min(num[l], min);
l = m + 1;
} else if (num[l] > num[m]) {
min = Math.min(num[m], min);
r = m - 1;
} else {
min = Math.min(num[m], min);
l++;
}
}
min = Math.min(num[r], min);
min = Math.min(num[l], min);
return min;
}
Better solution:
public int findMin(int[] num) {
int l = 0;
int r = num.length - 1;
while (l < r) {
int m = (l+r)/2;
//中间值大于起始值,且起始值大于终止值
if (num[m] >= num[l] && num[l] > num[r]) {
l = m + 1;
} else {
r = m;
}
}
return num[l];
}
No comments:
Post a Comment