Simple binary search solution in Java (O(log n))


  • 0
    T
    public class Solution {
        public int searchInsert(int[] nums, int target) {
            int low = 0;
            int high = nums.length-1;
            
            while (low < high) {
                int mid = (low+high+1)/2; // rounding up to avoid infinite loop when the array has 2 elements
                if (nums[mid] == target) {
                    return mid;
                }
                
                if (nums[mid] < target) {
                    low = mid;
                } else {
                    high = mid-1;
                }
            }
            if (nums[low] < target) {
                return low+1;
            }
            return low;
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.