Search Insert Position
2015-11-17 16:43
204 查看
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
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 binarySearch(int[] nums, int target) { int low = 0; int high = nums.length - 1; while(low <= high) { int mid = (low + high) / 2; if(nums[mid] == target) return mid; else if(nums[mid] > target) high = mid - 1; else low = mid + 1; } return low; } public int searchInsert(int[] nums, int target) { if(nums == null || nums.length == 0) throw new IllegalArgumentException(); return binarySearch(nums, target); } }
相关文章推荐
- matlab学习笔记(十一)---二值形态学运算
- 【leetcode】【89】Gray Code
- 【OC语法】Categeory(类目)的介绍
- xcode7/ios9中 低版本app运行时,屏幕上下出现黑边的问题
- JQuery AJax序列化元素
- 遍历Map的四种方法
- 3D引擎:Horde3D:小感3
- LeetCode:Remove Element
- 自定义UITableViewCell初始化代码
- 成为合法的苹果开发者
- poj 2586 Y2K Accounting Bug
- matlab并行编程SPMD
- MyBatis直接执行SQL查询及批量插入数据
- Subsets II
- WINDOWS网络编程接口
- Linux文件与目录管理
- Android.text.TextUtils类
- ON_COMMAND和ON_MESSAGE的区别
- 用java编程方式实现logback和log4j的自定义格式日志
- iconv 文件编码相互转换