[leetcode] 35. Search Insert Position
来源:互联网 发布:西西软件家园 编辑:程序博客网 时间:2024/05/16 01:10
Question:
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
Solution:
二分的升级版,要特别特别注意边界的情况就好。因为找不到也要返回应该出现的位置。
class Solution {public: int searchInsert(vector<int>& nums, int target) { int l = 0, mid, r = nums.size() - 1; while (l <= r) { mid = (l + r) / 2; if (nums[mid] == target) return mid; if (l == r) { if (target < nums[l]) return l; if (l + 1 == nums.size() || target < nums[l + 1]) return l + 1; return l + 2; } if (nums[mid] < target) { l = mid + 1; } else { r = mid; } } return -1; }};
阅读全文
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
- 35. Search Insert Position LeetCode
- [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
- Linux下的eeprom读写操作
- 函数声明后面的const用法 void function() const{}
- Linux vdso的系统调用
- Eclipse 设置编码格式为UTF-8
- float double 指定小数位数输出
- [leetcode] 35. Search Insert Position
- CSS布局系统
- web功能测试-输入框
- 百度地图调用
- iOS蓝牙开发CoreBluetooth框架总结
- 将 Intent 序列化,像 Uri 一样传递 Intent!!!
- codeforces——873A —— Chores
- AndroidApp混淆
- Centos 7 防火墙配置