【Leet Code】35. Search Insert Position---Medium

来源:互联网 发布:大华监控主机网络设置 编辑:程序博客网 时间:2024/06/08 09:30

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.

Here are few examples.
[1,3,5,6], 5 → 2
[1,3,5,6], 2 → 1
[1,3,5,6], 7 → 4

[1,3,5,6], 0 → 0


思路:

此题目就是一个很简单的查找,如果nums里面的值小于target值则将result值加1,并继续查找;

如果找到等于target的值,直接返回result的当前值。


代码实现:

class Solution {public:    int searchInsert(vector<int>& nums, int target) {        if(nums.size() < 1) return 0;        int result = 0;                for(auto num:nums)        {            if(num == target)                 return result;            if(num < target)                ++result;        }        return result;            }}


0 0
原创粉丝点击