[leetcode][search] Search Insert Position
来源:互联网 发布:美国时装画技法淘宝 编辑:程序博客网 时间:2024/06/06 11:39
题目:
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
class Solution {public: int searchInsert(vector<int>& nums, int target) { if(nums.empty()) return 0; return searchInsertCore(nums, 0, nums.size()-1, target); }private: int searchInsertCore(vector<int>& nums, int start, int end, int target){ if (start == end) return target <= nums[start] ? start : start+1;//!!!根据当前值和target的大小确定返回位置 int mid = (start+end) >> 1; if(target == nums[mid]) return mid; if(target > nums[mid]) return searchInsertCore(nums, mid+1, end, target); else return searchInsertCore(nums, start, mid, target);//如果start==mid,下次递归就会返回,不用mid-1,是为了防止越界,而且这样处理之后永远不会出现start>end的情况 }};
0 0
- [leetcode][search] Search Insert Position
- LeetCode: Search Insert Position
- LeetCode Search Insert Position
- [Leetcode] Search Insert Position
- LeetCode : Search Insert Position
- [LeetCode] Search Insert Position
- [Leetcode] Search Insert Position
- [LeetCode]Search Insert Position
- [LeetCode] Search Insert Position
- LeetCode-Search Insert Position
- LeetCode - Search Insert Position
- LeetCode | Search Insert Position
- Leetcode: Search Insert Position
- 【LeetCode】Search Insert Position
- Leetcode Search Insert Position
- Leetcode: Search Insert Position
- LeetCode:Search Insert Position
- leetcode Search Insert Position
- NSJSONSerialization
- 二、FPGA之模71计数器设计
- JavaScript 事件委托
- Bundle versions 与 Bundle versions string, short 的区别
- 输出链表倒数第K个节点
- [leetcode][search] Search Insert Position
- WiFi设备MAC地址的获取-----服务器端
- SSH纪实--最基本最基本的知识(一)
- Java中ArrayList类使用方法
- 等待网络操作须等待时的dialog
- Fragment和Activity
- Mybatis关联查询一对一和一对多的实现
- POJ 1279 || Art Gallery(半平面交求核面积
- spring hibernate下的懒加载问题