C++ solution with comment

  • 0
    class Solution {
        int searchInsert(vector<int>& nums, int target) {
            // if nothing found return the size, which is the out of range index
            int result = nums.size();
            for(int i = 0; i < nums.size(); i++) {
                // only need to find the first index of where it should insert, then we do not need to loop through the whole array.
                if (target <= nums[i]) {
                    result = i;
            return result;

Log in to reply

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