【LeetCode】35. 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
题意:找出指定元素的索引,如果没有这个元素,返回这个元素应该出现的位置
思路:二分法
1 class Solution { 2 public: 3 int searchInsert(vector<int>& nums, int target) { 4 int left=0,right=nums.size()-1; 5 while(left<=right){ 6 int mid=(left+right)/2; 7 if(nums[mid]<target) left=mid+1; 8 else right=mid-1; 9 } 10 return left; 11 } 12 13 };