33. Search in Rotated Sorted Array
Suppose a sorted array is rotated at some pivot unknown to you beforehand.
(i.e., 0 1 2 4 5 6 7
might become 4 5 6 7 0 1 2
).
You are given a target value to search. If found in the array return its index, otherwise return -1.
You may assume no duplicate exists in the array.
Hide Tags
Hide Similar Problems
(M) Search in Rotated Sorted Array II (M) Find Minimum in Rotated Sorted Array
public class Solution { public int search(int[] nums, int target) { int len = nums.length; int leftMin = nums[0]; int rightMax = nums[len - 1]; if (target > rightMax && target < leftMin) return -1; boolean targetAtLeft = target >= leftMin; int left = 0; int right = len - 1; while (left <= right) { int mid = (left + right) / 2; int midVal = nums[mid]; if (midVal == target) return mid; if (targetAtLeft) { if (midVal >= leftMin && midVal < target) left = mid + 1; // go right else right = mid - 1; //go left } else { if (midVal <= rightMax && midVal > target) right = mid - 1; // go left else left = mid + 1; //go right } } return -1; } }
81. Search in Rotated Sorted Array II
Follow up for "Search in Rotated Sorted Array":
What if duplicates are allowed?
Would this affect the run-time complexity? How and why?
Write a function to determine if a given target is in the array.
Hide Tags
Hide Similar Problems
(H) Search in Rotated Sorted Array
时间: 2024-12-25 14:09:24