Sharing my AC answers for Java and JavaScript


  • 0
    T

    JavaScript Version

    var searchInsert = function(nums, target) {
        'use strict';
        if(!nums) return 0;
        let left = 0, right = nums.length-1;
        if(target > nums[nums.length-1]) return nums.length;
        else if(target <= nums[0]) return 0;
        else {
            while(left <= right) {
                let mid = left + Math.floor((right-left)/2);
                if(nums[mid] === target) return mid;
                else if(nums[mid] > target) {
                    right = mid-1;
                } 
                else {
                    left = mid+1;
                }
            }
            return left;
        }
    };
    

    Java Version

    public class Solution {
        public int searchInsert(int[] nums, int target) {
            if(nums == null || nums.length == 0) return 0;
            int left = 0, right = nums.length-1;
            if(target > nums[nums.length-1]) return nums.length;
            else if(target <= nums[0]) return 0;
            else {
                while(left <= right) {
                    int mid = left + (right-left)/2;
                    if(nums[mid] == target) return mid;
                    else if(nums[mid] > target) {
                        right = mid-1;
                    }
                    else {
                        left = mid+1;
                    }
                }
                return left;
            }
        }
    }

Log in to reply
 

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