Skip to content

Commit

Permalink
Merge pull request neetcode-gh#2277 from zhrfrd/main
Browse files Browse the repository at this point in the history
Create 0034-find-first-and-last-position-of-element-in-sorted-array.java
  • Loading branch information
a93a authored Feb 22, 2023
2 parents adf1a86 + 2b08854 commit 44cb56b
Showing 1 changed file with 44 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
class Solution {
public int[] searchRange(int[] nums, int target) {
int left = 0;
int right = nums.length - 1;
int[] result = {-1, -1};

while (left <= right) {
int mid = left + ((right - left) / 2);

if (nums[mid] == target) {
result = findEdges(mid, nums, target);
break;
}

else if (target < nums[mid]) {
right = mid - 1;
}

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

return result;
}

public int[] findEdges(int mid, int[] nums, int target) {
int left = mid;
int right = mid;
int[] result = {left, right};

while (left >= 0 && nums[left] == target) {
result[0] = left;
left --;
}

while (right <= nums.length - 1 && nums[right] == target) {
result[1] = right;
right ++;
}

return result;
}
}

0 comments on commit 44cb56b

Please sign in to comment.