Search Insert Position--LeetCode
来源:互联网 发布:知乎PLUS 编辑:程序博客网 时间:2024/06/04 17:57
1.题目
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
2.题意
给定已排序的数组和目标值,如果找到目标值,则返回它的下标。如果找不到, 返回它应被插入的位置。假定数组中没有重复项。
3.分析
1)遍历数组,若nums[i]>=target,则返回i
如果target比nums中任何数都大,则返回数组长度
注意不要把return nums.size();写成别的数字
2)二分查找,时间复杂度是O(logn),空间复杂度是O(1)
如果数组中不存在target
left一定停在恰好比target大的index上
right一定停在恰好比target小的index上
4.代码
1)
class Solution {public: int searchInsert(vector<int>& nums, int target) { for(int i = 0; i < nums.size(); ++i) { if(nums[i] >= target) return i; } return nums.size(); }};
2)
class Solution {public: int searchInsert(vector<int>& nums, int target) { int len = nums.size(); if(len == 0) return 0; if(target <= nums[0]) return 0; if(target > nums[len - 1]) return len; int left = 0; int right = nums.size() - 1; while(left <= right) { int mid = left + (right - left) / 2; if(nums[mid] == target) return mid; else if(target < nums[mid]) right = mid - 1; else left = mid + 1; } return left; }};
阅读全文
0 0
- 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
- LeetCode Search Insert Position
- 各类user_segment移动表空间(table、lob、index)
- 对象的生命周期
- 膨胀腐蚀开运算闭运算
- 查询条件提交页面
- Java 接口、集成与多态
- Search Insert Position--LeetCode
- 集训Day2 T2 新壳栈
- HBase存储原理探究
- android 播放视频时切换全屏隐藏状态栏
- isalpha()实验
- 输入一个字符串然后把它反序输出
- python图像处理:CR2 to png
- 一个拥抱ARVR热点机会
- iOS去除UITableView左边15像素空白问题