11. The minimum number of rotation of the array to prove safety Offer

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
public class  {
public int minNumberInRotateArray(int[] array) {
int index1 = 0;
int index2 = array.length - 1;
int indexMid = 0;

if (array.length == 0) {
return 0;
}

while (array[index1] >= array[index2]) {
if (index2 - index1 == 1) {
indexMid = index2;
break;
}

indexMid = (index1 + index2) / 2;

if (array[index1] == array[indexMid] && array[indexMid] == array[index2]) {
return minSequentialSearch(array);
}

if (array[indexMid] >= array[index1]) {
index1 = indexMid;
} else if (array[indexMid] <= array[index2]) {
index2 = indexMid;
}
}

return array[indexMid];
}

private int minSequentialSearch(int[] array) {
int indexMin = 0;
for (int i = 1; i < array.length; i++) {
if (array[i] < array[indexMin]) {
indexMin = i;
}
}

return array[indexMin];
}
}

time complexity

The time complexity is logarithmic level $ O (logN) $.

Solution 2 [Java]: time complexity $ O (n / 2) $

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class  {
public int minNumberInRotateArray(int[] array) {
if (array.length == 0) {
return 0;
}

int min = array[0];

for (int i = 1; i < array.length; ++i) {
if (array[i] < min) {
return array[i];
}
}

Return min;
}
}

Thinking

After the rotation, from left to right comparison of two adjacent numbers will always find a set of numbers, the first number is greater than the second number, the second number is the minimum. Because the second number is the number of all subsequent rotation of the operation to move the last of a series of numbers.

Original: Big Box  prove safety 11. The minimum number of rotating array Offer


Guess you like

Origin www.cnblogs.com/chinatrump/p/11597040.html