Leetcode 33 Search in Rotated Sorted Array
程序员文章站
2022-07-16 11:56:53
...
Problem:
Analysis:
This question can be transferred as the above figure.
two scenarios: which represent by mid1 and mid2.
Code:
public int search(int[] nums, int target) {
if (nums.length == 0 || nums == null) {
return -1;
}
int left = 0, right = nums.length - 1;
while(left <= right) {
int mid = (left + right) / 2;
if (nums[mid] == target) {
return mid;
}else if (nums[mid] < nums[left]) {
if (nums[mid] < target && nums[right] >= target) {
left = mid + 1;
}else {
right = mid -1;
}
}else {
if (nums[left] <= target && nums[mid] > target) {
right = mid - 1;
}else {
left = mid + 1;
}
}
}
return -1;
}
推荐阅读
-
【LeetCode】Two Sum & Two Sum II - Input array is sorted & Two Sum IV - Input is a BST
-
Convert Sorted Array to Binary Search Tree
-
【一天一道LeetCode】#26. Remove Duplicates from Sorted Array
-
LeetCode 33. Search in Rotated Sorted Array && 81. Search in Rotated Sorted Array II
-
Leetcode 33 Search in Rotated Sorted Array
-
LeetCode·33. Search in Rotated Sorted Array
-
leetcode 33. Search in Rotated Sorted Array
-
0033_Search in Rotated Sorted Array
-
Search in Rotated Sorted Array II
-
33. Search in Rotated Sorted Array