题目
题解
代码
public class code33 {
// public static int search(int[] nums, int target) {
// for (int i = 0; i < nums.length; i++) {
// if (nums[i] == target) {
// return i;
// }
// }
// return -1;
// }
public static int search(int[] nums, int target) {
if (nums == null || nums.length == 0) {
return -1;
}
int left = 0;
int right = nums.length - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (nums[mid] == target) {
return mid;
} else if (nums[left] <= nums[mid]) {
if (nums[left] <= target && target < nums[mid]) {
right = mid - 1;
} else {
left = mid + 1;
}
} else if (nums[mid] <= nums[right]) {
if (nums[mid] < target && target <= nums[right]) {
left = mid + 1;
} else {
right = mid - 1;
}
}
}
return -1;
}
public static void main(String[] args) {
int nums[] = { 4, 5, 6, 7, 0, 1, 2 };
int target1 = 0;
int target2 = 3;
int index1 = search(nums, target1);
int index2 = search(nums, target2);
System.out.println(index1);
System.out.println(index2);
}
}