You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
To solve the "Search in Rotated Sorted Array" problem in Java with a `Solution` class, we can follow these steps:
40
+
41
+
1. Define a `Solution` class.
42
+
2. Define a method named `search` that takes an integer array `nums` and an integer `target` as input and returns an integer representing the index of `target` in `nums`. If `target` is not found, return `-1`.
43
+
3. Implement the binary search algorithm to find the index of `target` in the rotated sorted array.
44
+
4. Set the left pointer `left` to 0 and the right pointer `right` to the length of `nums` minus 1.
45
+
5. While `left` is less than or equal to `right`:
46
+
- Calculate the middle index `mid` as `(left + right) / 2`.
47
+
- If `nums[mid]` is equal to `target`, return `mid`.
48
+
- Check if the left half of the array (`nums[left]` to `nums[mid]`) is sorted:
49
+
- If `nums[left] <= nums[mid]` and `nums[left] <= target < nums[mid]`, update `right = mid - 1`.
50
+
- Otherwise, update `left = mid + 1`.
51
+
- Otherwise, check if the right half of the array (`nums[mid]` to `nums[right]`) is sorted:
52
+
- If `nums[mid] <= nums[right]` and `nums[mid] < target <= nums[right]`, update `left = mid + 1`.
53
+
- Otherwise, update `right = mid - 1`.
54
+
6. If `target` is not found, return `-1`.
55
+
56
+
Here's the implementation:
57
+
58
+
```java
59
+
publicclassSolution {
60
+
publicintsearch(int[] nums, inttarget) {
61
+
int left =0;
62
+
int right = nums.length -1;
63
+
64
+
while (left <= right) {
65
+
int mid = left + (right - left) /2;
66
+
67
+
if (nums[mid] == target) {
68
+
return mid;
69
+
}
70
+
71
+
if (nums[left] <= nums[mid]) {
72
+
if (nums[left] <= target && target < nums[mid]) {
73
+
right = mid -1;
74
+
} else {
75
+
left = mid +1;
76
+
}
77
+
} else {
78
+
if (nums[mid] < target && target <= nums[right]) {
79
+
left = mid +1;
80
+
} else {
81
+
right = mid -1;
82
+
}
83
+
}
84
+
}
85
+
86
+
return-1;
87
+
}
88
+
}
89
+
```
90
+
91
+
This implementation provides a solution to the "Search in Rotated Sorted Array" problem in Java. It searches for the index of `target` in the rotated sorted array `nums`. The algorithm has a time complexity of O(log n).
0 commit comments