leetcode解题报告(11):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

最简单的题目,没有之一

代码如下:

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

更优雅的解法是二分查找:

class Solution {
public:
    int searchInsert(vector<int>& nums, int target) {
        int low = 0,high = nums.size() - 1;
        while(low <= high){
            int mid = low + (high - low) / 2;
            if(nums[mid] < target)low = mid + 1;
            else    high = mid - 1;
        }
        return low;
    }
};
posted @ 2017-04-25 16:09  larryking  阅读(122)  评论(0编辑  收藏  举报