Java simple O(n) solution


  • 0
    M
    public class Solution {
        
        public int searchInsert(int[] nums, int target) {
            
            if (target < nums[0]) return 0;
            if (target > nums[nums.length-1]) return nums.length;
            
            for (int i = 0; i < nums.length; i++) {
                
                if (nums[i] == target) return i;
                
                if (target > nums[i] && target < nums[i+1]) return i+1;
            }
           
            return -1;
        }
    }
    

Log in to reply
 

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