欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

[leetcode]Search Insert Position

程序员文章站 2024-03-15 21:12:42
...

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

分析:

由于数组是排好序的,因此只要将要插入数字依次与数组内数字比较,大于等于要插入的数字时,其索引就是插入的位置

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

 

相关标签: LeetCode