Simple Java Solution


  • 0
    Q

    Since the array is already sorted, we just need to loop through the array and find the first index where the target is less or equal to the number. if not, increment index until the end, and the position will be the last index +1.

    public int searchInsert(int[] nums, int target) {
            int res = 0;
            for(int i=0; i<nums.length; i++){
                if(target<=nums[i] ){
                    return i;
                }else {
                    res = i+1;
                }
            }
            return res;
        }
    

Log in to reply
 

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