首页 > 学院 > 开发设计 > 正文

leetcode-35-Search Insert Position

2019-11-08 01:52:18
字体:
来源:转载
供稿:网友

问题

题目:[leetcode-35]

思路

二分查找,基础题。 但是,查找失败时的插入位置为high+1或者low

代码

class Solution {public: int searchInsert(vector<int>& nums, int target) { return biSearch( nums, 0, nums.size()-1, target ); }PRivate: int biSearch( const std::vector<int>& nums, int low, int high, int target ){ while(low <= high){ int mid = (low+high)/2; if(target == nums[mid]) return mid; else if( target < nums[mid] ) high = mid-1; else low = mid+1; } return high+1; }};
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表