https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/submissions/
Find Minimum in Rotated Sorted Array - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
* 오름차순 배열을 오른쪽으로 회전시킨 배열에서의 최소값을 구하는 문제
1. left < right 일 경우 오름차순의 순으로 되어 있는 배열이므로 nums[left] 가 최소값이 된다.
(left 이전의 값들은 이미 left의 값보다 크거나 없다.)
2. 1)의 경우에 해당되지 않는데 mid 값이 left 의 값보다 크다면 mid와 right 사이에 최소값이 존재한다고 볼 수 있으므로 left = mid+1
class Solution {
public int findMin(int[] nums) {
int left = 0;
int right = nums.length-1;
if(right == 0) return nums[0];
while(left <= right){
int mid = (left+ right)/2;
if(nums[left] <= nums[right]) return nums[left];
if(nums[mid] >= nums[left]){
left = mid+1;
} else {
right = mid;
}
}
return -1;
}
}
'코딩테스트 > LeetCode' 카테고리의 다른 글
[LeetCode]438. Find All Anagrams in a String (0) | 2022.11.07 |
---|---|
[LeetCode]54. Spiral Matrix (0) | 2022.11.04 |
[LeetCode]202. Happy Number (0) | 2022.11.03 |
[LeetCode]74. Search a 2D Matrix (0) | 2022.11.03 |
[LeetCode]34. Find First and Last Position of Element in Sorted Array (0) | 2022.11.02 |