LeetCode 35. Search insertion position (C ++)

Topic:
Given a sorted array and a target value, find the target value in the array and return its index. If the target value does not exist in the array, return the position where it will be inserted in order.
You can assume that there are no duplicate elements in the array.

Example 1:
Input: [1,3,5,6], 5
Output: 2

Example 2:
Input: [1,3,5,6], 2
Output: 1

Example 3:
Input: [1,3,5,6], 7
Output: 4

Example 4:
Input: [1,3,5,6], 0
Output: 0

Problem-solving ideas:
Because it is an ordered array, iterate through the array, find the first number greater than or equal to target, and return the subscript of this number.
If no numbers are found after the traversal, the size of the array is returned.

class Solution {
public:
    int searchInsert(vector<int>& nums, int target) {
        for(int i=0;i<nums.size();i++){
            if(target <= nums[i]){
                return i;
            }
        }
        return nums.size();
    }
};
Published 111 original articles · won praise 2 · Views 3533

Guess you like

Origin blog.csdn.net/m0_38088647/article/details/101796558