There is an integer array nums
sorted in ascending order (with distinct values).
Prior to being passed to your function, nums
is possibly rotated at an unknown pivot index k
(1 <= k < nums.length
) such that the resulting array is [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]]
(0-indexed). For example, [0,1,2,4,5,6,7]
might be rotated at pivot index 3 and become [4,5,6,7,0,1,2]
.
Given the array nums
after the possible rotation and an integer target
, return the index of target
if it is in nums
, or -1
if it is not in nums
.
You must write an algorithm with O(log n)
runtime complexity.
이분탐색 응용 문제였어요. 특정 부분 배열의 순서가 역전이 된 경우에 대한 target
의 위치를 찾는 문제였습니다. 의 속도로 찾으라 했으니, 역전된 부분을 순회해서 찾는건 불가능한 문제니까 결국엔 이분 탐색의 기준을 살짝 바꿔,
- 중간 값 ==
target
일 경우 반환start
~mid - 1
부분 이분 탐색target
을 못찾으면mid + 1
~end
부분 이분 탐색
기존 이분 탐색은 target
보다 작으면 우측만, target
보다 크면 좌측만 탐색하면 되는 방식을 조금 다르게 수정하니 매우 안정적으로 해결이 되었습니다.
class Solution {
public int search(int[] nums, int target) {
return binarySearch(nums, 0, nums.length - 1, target);
}
private int binarySearch(int[] nums, int start, int end, int target) {
if(start >= end)
return (nums[start] == target) ? start : -1;
int ret = -1;
int mid = (start + end) >>> 1;
if(nums[mid] == target){
ret = mid;
} else{
ret = binarySearch(nums, start, mid - 1, target);
if(ret < 0)
ret = binarySearch(nums, mid + 1, end, target);
}
return ret;
}
}