Leetcode (11) - Search for caret position

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, returns the position where it will be inserted in order.

You can assume that there are no duplicate elements in the array.

This topic is very simple, because it is a given sorted array and there are no repeated elements, so our first thought is to traverse the entire array and compare it with the target value. If it is equal, return its index. If it is greater than it, it must be the first A position greater than the target value, just return this position. If no match is found at the end, it will be inserted at the end.

class Solution {
public:
   int searchInsert(vector<int>& nums, int target) 
    {
        for(int i=0;i<nums.size();i++)
        {
            if(target==nums[i])
                return i;
            else if(target<nums[i])
                return i;
        }
        return nums.size();
    }
};

There is also a simpler solution, which is to borrow the lower_bound function in STL, which needs to include the algorithm header file when using it.

Containers in ascending order

iterator lower_bound( const key_type &key ): Returns an iterator pointing to the first element with key value >= key.

iterator upper_bound( const key_type &key ): Returns an iterator pointing to the first element with key value > key.

container in descending order

iteratorlower_bound( const key_type &key ): Returns an iterator pointing to the first element with key <= key.

iterator upper_bound( const key_type &key ): Returns an iterator pointing to the first element of key < key.

So the lower_bound function is appropriate here. Another thing to note is that it must be applied to sorted arrays.

int searchInsert(vector<int>& nums, int target) 
{
        auto idx=lower_bound(nums.begin(),nums.end(),target);
        return idx-nums.begin();
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325166552&siteId=291194637