Top 100
Find First and Last Position of Element
- Problem
- LC 34
- File
- top100_LC34FindFirstAndLastPositionOfElement.java
- Path
- pkg5leetcode/top100/top100_LC34FindFirstAndLastPositionOfElement.java
- Package
- pkg5leetcode.top100
- Command
- java pkg5leetcode/top100/top100_LC34FindFirstAndLastPositionOfElement.java
- Approach
- Two binary searches for leftmost and rightmost target.
- Complexity
- Time O(log n), Space O(1)
There is no in-browser runner. This is the file from the curriculum, unchanged.
1package pkg5leetcode.top100;2 3/*4 * Find First and Last Position of Element | LC 345 * APPROACH: Two binary searches for leftmost and rightmost target.6 * COMPLEXITY: Time O(log n), Space O(1)7 */8public class top100_LC34FindFirstAndLastPositionOfElement {9 static int[] searchRange(int[] nums, int target) {10 return new int[]{leftBound(nums, target), rightBound(nums, target)};11 }12 13 static int leftBound(int[] a, int t) {14 int lo = 0, hi = a.length - 1, res = -1;15 while (lo <= hi) {16 int mid = lo + (hi - lo) / 2;17 if (a[mid] >= t) hi = mid - 1;18 else lo = mid + 1;19 if (a[mid] == t) res = mid;20 }21 return res;22 }23 24 static int rightBound(int[] a, int t) {25 int lo = 0, hi = a.length - 1, res = -1;26 while (lo <= hi) {27 int mid = lo + (hi - lo) / 2;28 if (a[mid] <= t) lo = mid + 1;29 else hi = mid - 1;30 if (a[mid] == t) res = mid;31 }32 return res;33 }34 35 public static void main(String[] args) {36 check(java.util.Arrays.equals(searchRange(new int[]{5, 7, 7, 8, 8, 10}, 8), new int[]{3, 4}), "case1");37 check(java.util.Arrays.equals(searchRange(new int[]{5, 7, 7, 8, 8, 10}, 6), new int[]{-1, -1}), "case2");38 System.out.println("all tests passed");39 }40 41 static void check(boolean cond, String name) {42 if (!cond) throw new AssertionError("FAILED: " + name);43 System.out.println(" PASS " + name);44 }45}