Advertisement
1988coder

35. Search Insert Position

Jan 5th, 2019
130
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.12 KB | None | 0 0
  1. // LeetCode URL: https://leetcode.com/problems/search-insert-position/
  2. /**
  3.  * Binary Search
  4.  *
  5.  * We are trying to find the index of number equal to target or index of number
  6.  * just larger than target.
  7.  *
  8.  * Time Complexity: O(log N)
  9.  *
  10.  * Space Complexity: O(1)
  11.  *
  12.  * N = Lenght of the input array.
  13.  */
  14. class Solution {
  15.     public int searchInsert(int[] nums, int target) throws IllegalArgumentException {
  16.         if (nums == null) {
  17.             throw new IllegalArgumentException("Inout array is null");
  18.         }
  19.         if (nums.length == 0) {
  20.             return 0;
  21.         }
  22.  
  23.         int left = 0;
  24.         int right = nums.length; // This is valid as the target can be larger than all numbers in the array.
  25.  
  26.         while (left < right) {
  27.             int mid = left + (right - left) / 2;
  28.             if (nums[mid] >= target) {
  29.                 right = mid; // We are trying to find the index of number equal to target or index of number
  30.                              // just larger than target.
  31.             } else {
  32.                 left = mid + 1;
  33.             }
  34.         }
  35.  
  36.         return left;
  37.     }
  38. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement