JAVA solution--easy and clear

  • 0
    public class Solution {
    public int searchInsert(int[] nums, int target) {
        if(nums[0]>target){return 0;}
        if(nums.length==1 && nums[0]<target){
            return 1;
        for(int i=0;i<nums.length-1;i++){
            int n=i;
                return n;
            if(nums[i]<target && target<nums[i+1]){//i+1 so we need to consider len==1
                    return i+1;
        if(nums[nums.length-1]>=target)return nums.length-1;
        if(nums[nums.length-1]<target)return nums.length;
        return 0;


  • 0

    the last "return 0",does it matter?

  • 0

    yeah, for sure, the method requires to return a int

Log in to reply

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