LeetCode 35. Search Insert Position

来源:互联网 发布:超市行业数据 编辑:程序博客网 时间:2024/05/22 00:52

Search Insert Position


题目描述:

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,返回target在nums中的位置,如果nums中不包含target,那么返回target应该插入的位置。


题目代码:

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


原创粉丝点击