-
Notifications
You must be signed in to change notification settings - Fork 23
/
Find Minimum in Rotated Sorted Array II.java
executable file
·101 lines (82 loc) · 2.43 KB
/
Find Minimum in Rotated Sorted Array II.java
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
H
1520311890
tags: Array, Binary Search
一个需要严谨思考的题目. 因为有duplicate, 会导致不断平移, 所以最终time complexity是O(n)
所以不如直接扫一遍, 给出答案.
但是还是写一个Binary Search的样子, 只不过worst结果是O(n)
```
/*
Follow up for "Find Minimum in Rotated Sorted Array":
What if duplicates are allowed?
Would this affect the run-time complexity? How and why?
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.
The array may contain duplicates.
*/
/*
Thoughts:
Draw the graph, almost same with I.
If mid lands on duplicate && nums[mid]==nums[start], start++ until it does not equal.
Same for end, end-- untill it does not equal.
However:
Due to duplicates, it's possible for entire row to be same [2,2,2,2,2,2...2,2], which means the worst case is O(n)
Minght as well just find the min with O(n)
*/
class Solution {
public int findMin(int[] nums) {
if (nums == null || nums.length == 0) {
return 0;
}
int n = nums.length;
int start = 0;
int end = n - 1;
while (start + 1 < end) {
int mid = (start + end) >> 1;
if (nums[mid] == nums[end]) {
end--;
} else if (nums[mid] > nums[end]) {
start = mid;
} else {
end = mid;
}
}
return nums[start] < nums[end] ? nums[start] : nums[end];
}
}
/*
Medium Find Minimum in Rotated Sorted Array II My Submissions
40% Accepted
Suppose a sorted array 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.
The array may contain duplicates.
Example
Given [4,4,5,6,7,0,1,2] return 0
Tags Expand
Binary Search Divide and Conqueri
*/
/*
Previous notes
Thinking process:
It seems using binary search will leads to O(n), so just use a for loop with O(n)
*/
public class Solution {
/**
* @param num: a rotated sorted array
* @return: the minimum number in the array
*/
public int findMin(int[] num) {
if (num == null || num.length == 0) {
return -1;
}
int min = Integer.MAX_VALUE;
for (int i = 0; i < num.length; i++) {
if (min > num[i]) {
min = num[i];
}
}
return min;
}
}
```