leetcode-35. Search Insert Position
来源:互联网 发布:木材砍伐数据 编辑:程序博客网 时间:2024/05/20 05:08
leetcode-35. 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
这里首先排除首尾的特殊情况,即添加到0或者添加到nums.length-1的情况,然后再二分查找,只不过对于终止条件的判断需要注意一下,其他没有特别的。
public class Solution { public int searchInsert(int[] nums, int target) { int ret = 0,left = 0,right = nums.length-1; if(nums.length<1) return ret; if(nums[nums.length-1] < target) return nums.length; if(nums[0] >= target) return 0; while(left <= right){ ret = (left + right)/2; if(nums[ret]==target || (ret !=0 && nums[ret-1]<target && nums[ret]>target)) return ret; if(nums[ret]<target) left = ret + 1 ; if(nums[ret]>target) right = ret - 1 ; } return ret; }}
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
- 探讨Android 6.0及以上新权限系统的检测与处理
- leetcode(49).198. House Robber
- android中服务生命周期小结
- ubuntu下opencv的IDE——codeblocks
- Python中下划线---完全解读
- leetcode-35. Search Insert Position
- JS 日期格式化
- maven jetty 启动正常,运行却一直报404
- nyoj 求余数
- 客户端动态化系列之——URLRoute
- 欢迎使用CSDN-markdown编辑器
- 第十一周项目2—用二叉树求解代数表达式
- 剑指Offer——重建二叉树——C++
- 自定义竖直旋转显示文字的TextView