Search Insert Position
来源:互联网 发布:淘宝子账户认证 编辑:程序博客网 时间:2024/06/07 02:40
原题:
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
即给一个排好顺序的数组和一个整数,找到这个整数插到数组应该插的位置。
思考过程:
分析插入过程,所插位置一定是只比它大一点点的数字所在位置。如果是比数组最大元素更大的数就有区别。依旧用二叉搜索。
解题思路:
利用二叉搜索(应该搜不到这个数),达到只剩两个数字的范围。判断target和这两个数字大小,判断插入位置,如果target比最大的还大,那它就插在数组末尾。
结果代码:
public int searchInsert(int[] nums, int target) { if (nums.length == 0) return 0; return binarySearch(nums,0,nums.length - 1,target); } public int binarySearch(int[] nums,int l,int r,int target){ int medium = (l + r) / 2; if (medium == l) { if (nums[medium] >= target) return medium; if (nums[r] >= target) return r; else return r + 1; } if (nums[medium] > target) return binarySearch(nums,l,medium,target); else return binarySearch(nums,medium,r,target); }
阅读全文
0 0
- LeetCode: Search Insert Position
- Search Insert Position
- LeetCode Search Insert Position
- [Leetcode] Search Insert Position
- LeetCode : Search Insert Position
- Search Insert Position
- [LeetCode] Search Insert Position
- [Leetcode] Search Insert Position
- LeetCode34:Search Insert Position
- Search Insert Position
- [35]Search Insert Position
- Search Insert Position
- Search Insert Position
- [LeetCode]Search Insert Position
- Search Insert Position
- [LeetCode] Search Insert Position
- Search Insert Position
- Search Insert Position
- Solr Date类型的哪些你不得不了解的细节
- minGW下载与编译器安装
- erlang基础入门
- [BZOJ 2818] Gcd 线性筛+欧拉函数前缀和
- 栈的应用--括号匹配的检验
- Search Insert Position
- WIN7、WIN10下顺利使用S7-200编程软件的方法:
- 观察者模式OC版
- 条件随机场(CRF)
- 怎么限制一个应用程序进程使用指定的cpu
- DEV C++ 界面设置
- 欢迎使用CSDN-markdown编辑器
- idea安装步骤
- spark shuffle详解