153. Find Minimum in Rotated Sorted Array
Suppose an array of length n
sorted in ascending order is rotated between 1
and n
times.
nums = [0,1,2,4,5,6,7]
might become:[4,5,6,7,0,1,2]
if it was rotated 4 times.[0,1,2,4,5,6,7]
if it was rotated 7 times.Notice that rotating an array [a[0], a[1], a[2], ..., a[n-1]] 1 time results in the array [a[n-1], a[0], a[1], a[2], ..., a[n-2]].
Given the sorted rotated array nums
of unique elements, return the minimum element of this array.
You must write an algorithm that runs in O(log n)
time.
Input : 정렬된 상태에서 몇 칸 돌아가있는 array nums
Output : nums
원소 중 최소값
주어진 코드
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode() {}
TreeNode(int val) {this.val = val;}
TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
이진 탐색 이용
구현 방법 (이진 탐색 규칙)
start = middle
로 해준다.end = middle
로 해준다.예외 규칙
class Solution {
public int findMin(int[] nums) {
return findMin(nums, 0, nums.length - 1);
}
private int findMin(int[] nums, int start, int end) {
if (end - start <= 1) { // 원소가 2개 이하로 경우
return Math.min(nums[start], nums[end]);
}
if (nums[start] <= nums[end]) { // 정렬되어 있는 경우
return nums[start];
}
int middle = (start + end) / 2;
if (nums[middle] >= nums[start]) { // 중앙값이 앞 값보다 클 때
return findMin(nums, middle, end);
} else { // 중앙값이 뒤 값보다 작을 때
return findMin(nums, start, middle);
}
}
}