-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path153. Find Minimum in Rotated Sorted Array (Binary Search) 20.2.11 Medium
More file actions
81 lines (69 loc) · 3.11 KB
/
153. Find Minimum in Rotated Sorted Array (Binary Search) 20.2.11 Medium
File metadata and controls
81 lines (69 loc) · 3.11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
Suppose an array sorted in ascending order 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]).
Find the minimum element.
You may assume no duplicate exists in the array.
Example 1:
Input: [3,4,5,1,2]
Output: 1
Example 2:
Input: [4,5,6,7,0,1,2]
Output: 0
Solution: --------------------------------------------------------------------- Binary Search
----------------------------------------- O(logn) T, O(1) S
class Solution(object):
def findMin(self, nums):
if nums[len(nums) - 1] > nums[0] or len(nums) == 1: # Eliminate the case when the array is already sorted
# or the array only has one element
return nums[0]
left, right = 0, len(nums) - 1
while(left <= right):
middle = (left + right) / 2
if nums[middle] < nums[middle - 1]:
return nums[middle]
if nums[middle] > nums[middle + 1]: # To copy with situation like [2, 1]
return nums[middle + 1] # We need to consider both num[middle + 1] and nums[middle] to be the minimum
'''
Find the mid element of the array.
If mid element > first element of array this means that we need to look for the inflection point on the right of mid.
If mid element < first element of array this that we need to look for the inflection point on the left of mid.
'''
if nums[middle] > nums[0]: # THE KEY for every binary search problem is how we should
# update the left and right pointer
# In this example, this is also the MOST IMPORTANT PART !!!!!!!!!!!!!!!!!
# if nums[middle] > nums[0], then the upper half must be sorted,
# so we should focus on the latter half and assign left to mid + 1
# and vice versa.
left = middle + 1
elif nums[middle] < nums[0]:
right = middle - 1
"""
:type nums: List[int]
:rtype: int
"""
Java Version:
class Solution {
public int findMin(int[] nums) {
if (nums == null || nums.length == 0) {
return -1;
}
if (nums[nums.length - 1] > nums[0] || nums.length == 1) {
return nums[0];
}
int left = 0, right = nums.length - 1;
while (left <= right) {
int mid = (left + right) / 2;
if (mid + 1 < nums.length && nums[mid] > nums[mid + 1]) {
return nums[mid + 1];
}
if (mid - 1 >= 0 && nums[mid] < nums[mid - 1]) {
return nums[mid];
}
if (nums[left] > nums[mid]) {
right = mid - 1;
} else {
left = mid + 1;
}
}
return -1;
}
}