[LeetCode] 35. Search Insert Position

题目链接:传送门

Description

Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.

You may assume no duplicates 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 1:

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

Solution

题意:

给定一个有序数组和一个值target,找到target在插入改有序数组时应插入的位置

思路:

实际上就是找有序数组中 >=target 的第一个位置,直接找也行,其实这恰恰就是 lower_bound() 的功能

class Solution {
public:
    int searchInsert(vector<int>& nums, int target) {
        return lower_bound(nums.begin(), nums.end(), target) - nums.begin();
    }
};
posted @ 2018-02-21 00:53  酒晓语令  阅读(87)  评论(0编辑  收藏  举报