Skip to content

Commit

Permalink
Refine the solution for LC #33
Browse files Browse the repository at this point in the history
  • Loading branch information
rayworks committed Dec 20, 2023
1 parent b3878d5 commit 930dfa8
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 0 deletions.
37 changes: 37 additions & 0 deletions src/main/java/org/sean/array/ArraySearch.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,43 @@
* 33. Search in Rotated Sorted Array
*/
public class ArraySearch {
public int searchExt(int[] nums, int target) {
if (nums == null || nums.length == 0) {
return -1;
}
int left = 0;
int right = nums.length - 1;
while (left <= right) {
// check two ends
if (nums[left] == target) return left;
if (nums[right] == target) return right;

// eg:
//4567012
//5670124
int mid = left + (right - left) / 2;
if (nums[mid] == target) {
return mid;
} else if (nums[mid] > nums[left]) { // if it's already sorted in the left half
if (nums[mid] > target && nums[left] < target) { // check the target position in sorted range
right = mid - 1;
left++;
} else {
left = mid + 1;
}
} else {
// else right half is sorted
if (nums[mid] < target && nums[right] > target) {
left = mid + 1;
right--;
} else {
right = mid - 1;
}
}
}
return -1;
}

// region Time O(logN)
private int doBinSearch(int[] nums, int l, int r, int target) {
while (l <= r) {
Expand Down
8 changes: 8 additions & 0 deletions src/test/java/org/sean/array/ArraySearchTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -18,4 +18,12 @@ public void setUp() throws Exception {
public void search() {
assertEquals(-1, finder.search(new int[]{4, 5, 6, 7, 0, 1, 2}, 3));
}

@Test
public void testSearch() {
assertEquals(-1, finder.searchExt(new int[]{4, 5, 6, 7, 0, 1, 2}, 3));
assertEquals(4, finder.searchExt(new int[]{4, 5, 6, 7, 0, 1, 2}, 0));
assertEquals(0, finder.searchExt(new int[]{4, 5, 6, 7, 0, 1, 2}, 4));
assertEquals(6, finder.searchExt(new int[]{4, 5, 6, 7, 0, 1, 2}, 2));
}
}

0 comments on commit 930dfa8

Please sign in to comment.