LeetCode进阶之路( Search Insert Position)
来源:互联网 发布:单片机开发系统有哪些 编辑:程序博客网 时间:2024/04/28 23:23
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,如果能找到,返回该值的位置;如果找不到,返回该插入的位置。
思路:用二分法找。
public int searchInsert(int[] nums, int target) { int left = 0; int right = nums.length - 1; if(target < nums[left]) {//小于最小值,该插入0位置 return 0; } if(target > nums[right]) {//大于最大值,该插入最后一个位置 return nums.length; } while(left <= right) { int mid = (right + left)/2; if(nums[mid] == target) {//恰好是中间值,返回mid return mid; } else if(nums[mid] > target && nums[mid-1] < target) {//如果小于中间值,且大于前一位,返回mid return mid; } else if(nums[mid] < target && nums[mid+1] > target ) {//如果大于中间值,且小于后一位,返回mid+1 return mid+1; } if(nums[mid] > target) {//继续二分发寻找合适的位置 right = mid - 1; } else { left = mid + 1; } } return 0; }
0 0
- LeetCode进阶之路( Search Insert Position)
- leetcode之路035 Search Insert Position
- LeetCode之Search Insert Position(C++)
- 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 OJ 之 Search Insert Position (查找插入位置)
- Leetcode之Search Insert Position 问题
- LeetCode: Search Insert Position
- LeetCode Search Insert Position
- JavaScript中的事件处理
- jQuery表单、表格的操作总结
- hdoj5792求四元组的个数(容斥+树状数组)
- ScrollView的生命周期
- windows下搭建Darwin流媒体服务器
- LeetCode进阶之路( Search Insert Position)
- 八大排序之堆排序
- hdu 4405 Aeroplane chess(概率dp)
- REDIS学习(2)常用命令
- mongodb简单入门
- ArrayList 和 Vector 的区别 -JAVA
- 001——struts 2的架构以及运行流程
- pycharm 虚拟环境如何手动安装第三方包(附带pywin32在windows的安装)
- 访问tomcat出现java.lang.IllegalStateException No output folder错误解决方法