-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrasduplicates2.java
More file actions
51 lines (46 loc) · 1.61 KB
/
rasduplicates2.java
File metadata and controls
51 lines (46 loc) · 1.61 KB
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
import java.util.*;
public class rasduplicates2 {
public static boolean searchInARotatedSortedArrayII(int []arr, int k) {
int n = arr.length; // size of the array.
int low = 0, high = n - 1;
while (low <= high) {
int mid = (low + high) / 2;
//if mid points the target
if (arr[mid] == k) return true;
//Edge case:
if (arr[low] == arr[mid] && arr[mid] == arr[high]) {
low = low + 1;
high = high - 1;
continue;
}
//if left part is sorted:
if (arr[low] <= arr[mid]) {
if (arr[low] <= k && k <= arr[mid]) {
//element exists:
high = mid - 1;
} else {
//element does not exist:
low = mid + 1;
}
} else { //if right part is sorted:
if (arr[mid] <= k && k <= arr[high]) {
//element exists:
low = mid + 1;
} else {
//element does not exist:
high = mid - 1;
}
}
}
return false;
}
public static void main(String[] args) {
int[] arr = {7, 8, 1, 2, 3, 3, 3, 4, 5, 6};
int k = 3;
boolean ans = searchInARotatedSortedArrayII(arr, k);
if (ans == false)
System.out.println("Target is not present.");
else
System.out.println("Target is present in the array.");
}
}