[LeetCode] Search Insert Position

来源:互联网 发布:sqlserver完全卸载 编辑:程序博客网 时间:2024/05/19 00:13

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

题目比较简单,直接二分查找,常规的循环退出时返回-1说明没有找到,现在根据退出时front和rear位置来返回应该插入的位置
稍加分析可以知,直接返回front位置即可

class Solution {public:    int searchInsert(vector<int>& nums, int target) {        int front = 0, rear = nums.size()-1;        int center;        while(front<=rear){            center = (front+rear)/2;            if(nums[center]==target)                return center;            else if(target>nums[center])                    front = center+1;            else                    rear = center-1;        }        return front;    }};
0 0
原创粉丝点击