标签:
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
Array Binary Search
这道题是个简单题,没啥说的
#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