My Accepted Java solution


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

    }


  • 0
    D

    Binary search will do better here with O(log n). Also, in your solution, you don't have to check both current and next element in the array since it's already sorted. Check the current element, and if it's greater than or equal to target, then its place needs to be given to target.


Log in to reply
 

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