[Leetcode] 154. Find Minimum in Rotated Sorted Array II
2024. 4. 10. 09:20ㆍAlgorithm
Problem:
Suppose an array of length n sorted in ascending order is rotated between 1 and n times. For example, the array nums = [0,1,4,4,5,6,7] might become:
[4,5,6,7,0,1,4] if it was rotated 4 times.
[0,1,4,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 that may contain duplicates, return the minimum element of this array.
You must decrease the overall operation steps as much as possible.
Example 1:
Input: nums = [1,3,5]
Output: 1
Example 2:
Input: nums = [2,2,2,0,1]
Output: 0
Constraints:
n == nums.length
1 <= n <= 5000
-5000 <= nums[i] <= 5000
nums is sorted and rotated between 1 and n times.
Solution:
class Solution:
def findMin(self, nums: List[int]) -> int:
left,right = 0 , len(nums) -1
mid = 0
while left < right:
mid = (left + right) // 2
if nums[mid] == nums[right]:
right -= 1
elif nums[mid] < nums[right]:
right = mid
else:
left = mid + 1
return nums[left]
위 Solution은 다른 사람의 Solution을 참고하여 작성했다. duplicates가 있기 때문에 Binary Search를 어떻게 써야 할지 고민을 많이 했다. 내가 생각하지 못한 부분은 nums [mid]와 nums [right]가 같을 때, right -= 1을 해주는 부분이다. 이때 내가 깨달은 것은 right에 1을 빼주면 mid값도 순차적으로 줄어들어서 모든 경우의 수를 경험한다는 것이다.
'Algorithm' 카테고리의 다른 글
[Leetcode]509. Fibonacci Number (0) | 2024.07.19 |
---|---|
[Leetcode]206. Reverse Linked List (0) | 2024.07.17 |
[Leetcode] 153. Find Minimum in Rotated Sorted Array (0) | 2024.04.08 |
[Leetcode] 81. Search in Rotated Sorted Array II (0) | 2024.04.08 |
[Leetcode] 74. Search a 2D Matrix (0) | 2024.04.04 |