My java solution use binary search

  • 0
    public class Solution {
    public int searchInsert(int[] nums, int target) {
        int n = nums.length;
        if(n==0 || nums[0]>target) return 0;
        int start =0;
        int end =n-1;
            int mid = start+(end-start)/2;
            if(nums[mid]==target) return mid;
            if(mid+1<n&&nums[mid]<target&&nums[mid+1]>target) return mid+1;
            if(nums[mid]<target) start=mid+1;
            else end=mid;
        return n;


Log in to reply

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