Skip to content

Commit

Permalink
Merge pull request #201 from AlgoLeadMe/8-mjj111
Browse files Browse the repository at this point in the history
8-mjj111
  • Loading branch information
9kyo-hwang authored Sep 10, 2024
2 parents 8fe948d + 425914c commit 27fed16
Showing 1 changed file with 44 additions and 0 deletions.
44 changes: 44 additions & 0 deletions mjj111/SearchForARange.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
class SearchForARange {
public int[] searchRange(int[] nums, int target) {
int firstOccurrence = this.findBound(nums, target, true);

if (firstOccurrence == -1) {
return new int[] { -1, -1 };
}

int lastOccurrence = this.findBound(nums, target, false);

return new int[] { firstOccurrence, lastOccurrence };
}

private int findBound(int[] nums, int target, boolean isFirst) {
int N = nums.length;
int begin = 0, end = N - 1;

while (begin <= end) {
int mid = (begin + end) / 2;

if (nums[mid] == target) {
if (isFirst) {
if (mid == begin || nums[mid - 1] != target) {
return mid;
}

end = mid - 1;
} else {
if (mid == end || nums[mid + 1] != target) {
return mid;
}

begin = mid + 1;
}
} else if (nums[mid] > target) {
end = mid - 1;
} else {
begin = mid + 1;
}
}

return -1;
}
}

0 comments on commit 27fed16

Please sign in to comment.