Why my java binary search is so slow?


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

    Standard binary search, 8ms and beat only 2%... Any idea why?


  • 0
    Z

    This time is not always right and percise. Sometimes I submitted a same code twice, it gave me two different times.


  • 0
    L

    The same code get 0ms two months ago, but 6ms to 8ms now


Log in to reply
 

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