Three concise Java solutions


  • 0

    Here are the codes by searching from the left, right, and always searching the middle.

    //Search from the most left
     public int searchInsert(int[] nums, int target) {
            if(nums == null) return 0;
            int res = 0;
            for(int num : nums) {
                if(num >= target) break;
                res++;
            }
            return res;
     }
    
    //Always search the middle
     public int searchInsert(int[] nums, int target) {
             if(nums == null) return 0;
             int index = 0, bound = nums.length;
             while(index < bound) {
                int mid = index + (bound - index) / 2;
                if (target > nums[mid]) index = mid + 1;
                else bound = mid; 
             }
             return index;
     }
    
     //Search from the most right
     public int searchInsert(int[] nums, int target) {
            if(nums == null) return 0;
            int res = nums.length;
            for(int i = nums.length - 1; i >= 0; i-- ) {
                if(nums[i] < target) break;
                res--;
            }
            return res;
    }
    

Log in to reply
 

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