LeetCode 35. Search Insert Position(搜索插入点)
2016-05-20 10:37
597 查看
原题网址:https://leetcode.com/problems/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.
方法:二分法查找。
二分法查找其实i<=j或者i<j作为条件都是可以的,不过前者用得比较顺。
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
方法:二分法查找。
public class Solution { public int searchInsert(int[] nums, int target) { int i=0, j=nums.length-1; while (i<=j) { int m = (i+j)/2; if (target == nums[m]) return m; if (target < nums[m]) { j = m - 1; } else { i = m + 1; } } return i; } }
二分法查找其实i<=j或者i<j作为条件都是可以的,不过前者用得比较顺。
public class Solution { public int searchInsert(int[] nums, int target) { int i=0, j=nums.length-1; while (i<j) { int m = (i+j)/2; if (target == nums[m]) return m; if (target < nums[m]) { j = m; } else { i = m + 1; } } if (target > nums[i]) return i+1; return i; } }
相关文章推荐
- 转 linux任务调度之crontab命令
- linux服务器启动过程
- A Fully Featured Windows HTTP Wrapper in C++
- 11.进程间通信---网络通信(基于socket的一对一通信模型)
- USB协议架构及驱动架构
- c++第六次实验-2
- spring---注解@Resource和@Autowired
- c语言发送邮件
- Android中Handler的作用和使用方法
- web端文件上传功能的思考
- MultipeerConnectivity.framework梳理
- 日期处理3
- Spring mvc 视图解析器 ContentNegotiatingViewResolver 源码分析
- LeetCode 31. Next Permutation(下一个排列)
- LeetCode 32. Longest Valid Parentheses(最长有效括号)
- LeetCode 33. Search in Rotated Sorted Array(旋转数组搜索)
- LeetCode 34. Search for a Range(搜索范围)
- git命令详解(转)
- Murano Weekly Meeting 2016.05.10
- UD三分区补充教程1——激活不同分区对于UD三分区bios启动和uefi启动兼容性影响的讨论