-
Notifications
You must be signed in to change notification settings - Fork 15
/
find-minimum-in-rotated-sorted-array.java
69 lines (60 loc) · 1.86 KB
/
find-minimum-in-rotated-sorted-array.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
public class Solution {
/**
* @param num: a rotated sorted array
* @return: the minimum number in the array
*/
public int findMin(int[] num) {
// write your code here
int len = num.length;
if (len == 0) {
return 0;
}
return minHelper(num, 0, len - 1);
}
public int minHelper(int[] num, int start, int end) {
if (start == end) {
return num[start];
}
int mid = (start + end) / 2;
if (num[start] < num[mid]) {
// left half is sorted
int leftMin = num[start];
int rightMin = minHelper(num, mid + 1, end);
return leftMin < rightMin? leftMin : rightMin;
} else {
int rightMin = num[mid + 1];
int leftMin = minHelper(num, start, mid);
return leftMin < rightMin? leftMin : rightMin;
}
}
}
public class Solution {
/**
* @param num: a rotated sorted array
* @return: the minimum number in the array
*/
public int findMin(int[] num) {
// write your code here
int len = num.length;
if (len == 0) {
return 0;
}
return minHelper(num, 0, len - 1);
}
public int minHelper(int[] num, int start, int end) {
if (start + 1 == end) {
return num[start] < num[end]? num[start] : num[end];
}
int mid = (start + end) / 2;
if (num[start] < num[mid]) {
// left half is sorted
int leftMin = num[start];
int rightMin = minHelper(num, mid , end);
return leftMin < rightMin? leftMin : rightMin;
} else {
int rightMin = num[mid];
int leftMin = minHelper(num, start, mid);
return leftMin < rightMin? leftMin : rightMin;
}
}
}