Search Insert Position
Total Accepted: 56150 Total Submissions: 158216My Submissions
Question Solution
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
Have you met this question in a real interview?
Yes
No
这道题是个简单题,没啥说的
#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; }
时间: 2024-10-05 15:44:42