码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode-Search Insert Position

时间:2015-05-11 09:07:32      阅读:142      评论:0      收藏:0      [点我收藏+]

标签:

题目描述

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

解题思路

方法一,从前往后找,当target小于或者等于数组中某个数的时候,就返回这个数的下标即可,代码如下;
class Solution {
public:
    int searchInsert(vector<int>& nums, int target) {
        if(nums.size()==0) return 0;
        int flag=-1;
        for(int i=0;i<nums.size();i++)
        {
            if(target<=nums[i])
            {
                flag=i;
                break;
            }
        }
        if(flag==-1)
        {
            flag=nums.size();
        }
        return flag;
    }
};

方法二,利用二分查找法
代码如下:
class Solution {
public:
    int searchInsert(vector<int>& nums, int target) {
        if(nums.size()==0) return 0;
        int low=0,high=nums.size()-1;
        while(low<=high)
        {
            int mid=(low+high)/2;
            if(target>nums[mid]) low=mid+1;
            else if(target<nums[mid]) high=mid-1;
            else return mid;
            
        }
    }
};


leetcode-Search Insert Position

标签:

原文地址:http://blog.csdn.net/sinat_24520925/article/details/45623345

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!