LeetCode 35 Search Insert Position
来源:互联网 发布:大数据 图书 编辑:程序博客网 时间:2024/05/29 02:24
题目:
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
题意:
给一个从小到大排好序的数组和一个目标值,要求如果数组中存在该目标值的话就返回其下标,否则返回按升序插入后的位置下标。
我的思路是二分查找,之后判断nums[l]与target的关系,假如target大于nums[l],说明应该插入到 l 的右边,否则插入到其左边。
代码如下:
class Solution {public: int searchInsert(vector<int>& nums, int target) { int l = 0, r = nums.size() - 1; while (l < r) { int mid = (l + r) / 2; if (nums[mid] == target) return mid; if (nums[mid] > target) { r = mid; } else { l = mid + 1; } } return l + (nums[l] < target ? 1 : 0); }};
阅读全文
0 0
- leetcode 35: Search Insert Position
- Leetcode(35) Search Insert Position
- [leetcode 35] Search Insert Position
- [Leetcode] 35 - Search Insert Position
- LeetCode 35 Search Insert Position
- leetcode-35 Search Insert Position
- LeetCode 35 Search Insert Position
- Leetcode 35 Search Insert Position
- Leetcode[35]-Search Insert Position
- LeetCode 35:Search Insert Position
- leetcode-35-Search Insert Position
- leetcode 35 -- Search Insert Position
- leetcode[35]:Search Insert Position
- leetcode 35: Search Insert Position
- Leetcode#35 Search Insert Position
- LeetCode(35) Search Insert Position
- LeetCode 35: Search Insert Position
- Leetcode#35||Search Insert Position
- 基于Springboot-Netty-Protostuff-ZooKeeper分布式RPC框架
- HDU 6059 Kanade's trio 字典树
- Windows配置node环境以及express模块
- java7 [try-with-resources]
- mycat
- LeetCode 35 Search Insert Position
- 串结构练习——字符串连接
- Unix编程学习笔记----对系统调用的完全理解
- 经历过的都是收获
- 【pytorch源码赏析】nn.XX VS nn.functional.XX
- 华为软件开发云对比Jenkins-JavaWeb项目持续部署方式
- 分布式协调服务Zookeeper
- PHP文件上传问题
- python通过正则表达式提取文本