Java non-recursive binary search solution


  • 0
    A
    public class Solution {
        public int searchInsert(int[] nums, int target) {
            int len = nums.length;
            if (len<1) return 0;
            int lo=0, hi=len-1;
            while (lo <= hi) {
                if (target < nums[lo])
                    return lo;
                if (target > nums[hi])
                    return (hi+1);
                int mid = (lo + hi)/2;
                if (target < nums[mid])
                    hi = mid-1;
                else if (target > nums[mid])
                    lo = mid+1;
                else
                    return mid;
            }
            return -1;  // unnecessary
        }
    }

Log in to reply
 

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