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
60 lines (52 loc) · 1.85 KB

File metadata and controls

60 lines (52 loc) · 1.85 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
package Algorithms.array;
/*
* https://oj.leetcode.com/problems/search-in-rotated-sorted-array-ii/
*
* Search in Rotated Sorted Array II Total Accepted: 18427 Total Submissions: 59728 My Submissions
Follow up for "Search in Rotated Sorted Array":
What if duplicates are allowed?
Would this affect the run-time complexity? How and why?
Write a function to determine if a given target is in the array.
* */
public class SearchInRotatedSortedArray2 {
/*
In this function, the complex may go to O(n). It depents on how many duplicates exit in the array.
if there are M duplicates, the complexity may be O(logN + M).
*/
public boolean search(int[] A, int target) {
if (A == null || A.length == 0) {
return false;
}
// setup two point to the left and right of the array.
int l = 0, r = A.length - 1;
while (l <= r) {
// get the mid point.
int mid = l + (r - l)/2;
if (target == A[mid]) {
return true;
}
if (A[mid] > A[l]) {
// the left side is sorted.
if (target <= A[mid] && target >= A[l]) {
// target is in the left side.
r = mid - 1;
} else {
l = mid + 1;
}
} else if (A[mid] < A[l]) {
// the right side is sorted.
if (target <= A[r] && target >= A[mid]) {
// target is in the right side.
l = mid + 1;
} else {
r = mid - 1;
}
} else {
// when A[mid] == A[l], we can't determin, just move the
// left point one
l++;
}
}
return false;
}
}
Morty Proxy This is a proxified and sanitized view of the page, visit original site.