欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

[leetcode]Search Insert Position

程序员文章站 2024-03-15 21:34:54
...

新博文地址:[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;
    }