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

leetcode_35题——Search Insert Position(二分查找)

时间:2015-05-26 10:42:07      阅读:127      评论:0      收藏:0      [点我收藏+]

标签:

Search Insert Position

 Total Accepted: 56150 Total Submissions: 158216My Submissions

 

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

 

Hide Tags
 Array Binary Search
Have you met this question in a real interview? 
Yes
 
No
 

Discuss

       这道题是个简单题,没啥说的

#include<iostream>
#include<vector>
using namespace std;
int searchInsert(vector<int>& nums, int target) {
	if(nums.empty())
		return 0;
	int x=0;
	int y=nums.size()-1;
	while(1)
	{
		if(x==y)
			if(target<=nums[x])
				return x;
			else 
				return x+1;
		int z=(y-x)/2+x;
		
		if(target==nums[z])
			return z;
		else if(target>nums[z])
			x=z+1;
		else
			y=z;
	}
}
int main()
{
	vector<int> vec;
	vec.push_back(1);vec.push_back(3);vec.push_back(5);vec.push_back(6);
	cout<<searchInsert(vec,7)<<endl;
}

  

leetcode_35题——Search Insert Position(二分查找)

标签:

原文地址:http://www.cnblogs.com/yanliang12138/p/4529860.html

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