Interview 150
Search Insert Position
- Problem
- LC 35
- File
- interview150_LC35SearchInsertPosition.java
- Path
- pkg5leetcode/interview150/interview150_LC35SearchInsertPosition.java
- Package
- pkg5leetcode.interview150
- Command
- java pkg5leetcode/interview150/interview150_LC35SearchInsertPosition.java
- Approach
- Binary search for first index where nums[i] >= 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.interview150;2 3/*4 * Search Insert Position | LC 355 * APPROACH: Binary search for first index where nums[i] >= target.6 * COMPLEXITY: Time O(log n), Space O(1)7 */8public class interview150_LC35SearchInsertPosition {9 static int searchInsert(int[] nums, int target) {10 int lo = 0, hi = nums.length;11 while (lo < hi) {12 int mid = (lo + hi) / 2;13 if (nums[mid] < target) lo = mid + 1;14 else hi = mid;15 }16 return lo;17 }18 19 public static void main(String[] args) {20 check(searchInsert(new int[]{1, 3, 5, 6}, 5) == 2, "case1");21 check(searchInsert(new int[]{1, 3, 5, 6}, 2) == 1, "case2");22 check(searchInsert(new int[]{1, 3, 5, 6}, 7) == 4, "case3");23 System.out.println("all tests passed");24 }25 26 static void check(boolean cond, String name) {27 if (!cond) throw new AssertionError("FAILED: " + name);28 System.out.println(" PASS " + name);29 }30}