Leetcode81: Search Insert Position

来源:互联网 发布:淘宝店刷销量方法 编辑:程序博客网 时间:2024/05/22 03:27

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

两种方法,一种直接遍历,一种二分查找

class Solution {public:    int searchInsert(vector<int>& nums, int target) {        int size = nums.size();        if(size == 0)            return 0;        int i;        for(i = 0; i < size; i++)        {            if(target <= nums[i])                return i;        }        return i;    }};
class Solution {public:    int searchInsert(vector<int>& nums, int target) {        int size = nums.size();        int low = 0, high = size-1;        while(low <= high) {            int mid = (low+high)>>1;            if(nums[mid] == target)                 return mid;            else if(nums[mid] > target)                 high = mid-1;            else                low = mid+1;        }        if(high < 0) return 0;        if(low >= size) return size;        return low;    }};



0 0