Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Latest commit

 

History

History
History
121 lines (103 loc) · 3.28 KB

File metadata and controls

121 lines (103 loc) · 3.28 KB
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
package Algorithms.array;
public class SearchInRotatedSortedArray {
public int search(int[] A, int target) {
if (A == null || A.length == 0) {
return -1;
}
int left = 0;
int right = A.length - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (A[mid] == target) {
return mid;
}
// the left side is sorted.
if (A[mid] >= A[left]) {
if (target <= A[mid] && target >= A[left]) {
// target is in the left side.
right = mid - 1;
} else {
// target is in the right side.
left = mid + 1;
}
} else { // the right side is sorted.
if (target >= A[mid] && target <= A[right]) {
// target is in the right side.
left = mid + 1;
} else {
// target is in the right side.
right = mid - 1;
}
}
}
return -1;
}
// 2015.1.1 redo:
public int search1(int[] A, int target) {
if (A == null || A.length == 0) {
return -1;
}
int l = 0;
int r = A.length - 1;
while (l < r - 1) {
int mid = l + (r - l) / 2;
if (A[mid] == target) {
return mid;
}
// left side is sorted.
// BUG 1: if don't use >= , and use L < r in while loop, than there is some problem.
if (A[mid] > A[l]) {
if (target > A[mid] || target < A[l]) {
// move to right;
l = mid + 1;
} else {
r = mid - 1;
}
} else {
if (target < A[mid] || target > A[r]) {
// move to left;
r = mid - 1;
} else {
l = mid + 1;
}
}
}
if (A[l] == target) {
return l;
} else if (A[r] == target) {
return r;
}
return -1;
}
public int search2(int[] A, int target) {
if (A == null || A.length == 0) {
return -1;
}
int l = 0;
int r = A.length - 1;
while (l <= r) {
int mid = l + (r - l) / 2;
if (A[mid] == target) {
return mid;
}
// left side is sorted.
// BUG 1: if don't use >= , and use L < r in while loop, than there is some problem.
if (A[mid] >= A[l]) {
if (target > A[mid] || target < A[l]) {
// move to right;
l = mid + 1;
} else {
r = mid - 1;
}
} else {
if (target < A[mid] || target > A[r]) {
// move to left;
r = mid - 1;
} else {
l = mid + 1;
}
}
}
return -1;
}
}
Morty Proxy This is a proxified and sanitized view of the page, visit original site.