解:
class Solution {
public int search(int[] nums, int target) {
if (nums == null || nums.length == 0) {
return -1;
}
if (nums.length == 1) {
return (nums[0] == target) ? 0:-1;
}
int low = 0;
int high = nums.length - 1;
while(low <= high) {
int mid = (low + high) >> 1;
if (nums[mid] == target) {
return mid;
} else if (nums[mid] > target) {
high = mid - 1;
} else {
low = mid + 1;
}
}
return -1;
}
}
/**
* 测试用例 nums: [-1] ; target: 1
[1, 3]; target 5;
*/
网友评论