-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsearchrotatedII.java
83 lines (75 loc) · 2.38 KB
/
searchrotatedII.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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
public class searchrotatedII {
public static void main(String[] args) {
int[] arr = { 2, 5, 6, 88, 0, 1, 2 };
int target = 8;
boolean sec = search(arr, target);
System.out.println(sec);
// for (int i = 0; i < sec.length; i++) {
// System.out.println(sec[i]);
// }
}
// Approach 2
public static boolean search(int[] nums, int target) {
int low = 0, high = nums.length - 1;
while (low <= high) {
int mid = low + (high - low) / 2;
// If found the target, return true
if (nums[mid] == target) {
return true;
}
// Handle duplicates (skip them)
if (nums[low] == nums[mid] && nums[mid] == nums[high]) {
low++;
high--;
continue;
}
// Check if left half is sorted
if (nums[low] <= nums[mid]) {
// If target is in the sorted left half
if (nums[low] <= target && target < nums[mid]) {
high = mid - 1;
} else {
low = mid + 1;
}
}
// Otherwise, the right half is sorted
else {
// If target is in the sorted right half
if (nums[mid] < target && target <= nums[high]) {
low = mid + 1;
} else {
high = mid - 1;
}
}
}
// Target not found
return false;
}
public static int[] searchrotatedIIi(int[] arr, int target) {
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr.length; j++) {
if (arr[i] < arr[j]) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
int low = 0;
int high = arr.length - 1;
boolean found = false;
while (low <= high) {
int mid = low + ((high - low) / 2);
if (arr[mid] == target) {
found = true;
break;
} else if (arr[mid] < target) {
low = mid + 1;
} else if (arr[mid] > target) {
high = mid - 1;
}
}
System.out.println(found);
return arr;
}
}