`
huntfor
  • 浏览: 195500 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

[leetcode]Search Insert Position

 
阅读更多

新博文地址:[leetcode]Search Insert Position

http://oj.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.
[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 int searchInsert(int[] a, int target) {
        	int begin = 0 ;
		int end = a.length - 1;
		while(begin <= end){
			int mid = ( begin + end ) >> 1;
			if(a[mid] == target){
				return mid;
			}else if(a[mid] > target){
				end = mid - 1;
			}else{
				begin = mid + 1;
			}
		}
		return begin;
    }

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics