LeetCode——Search Insert Position

来源:互联网 发布:python获取当前路径 编辑:程序博客网 时间:2024/05/16 02:33

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

Java代码:

public class Solution {    public int searchInsert(int[] A, int target) {        int len = A.length;                int start =0;        int end = len-1;        int index =0;                for(;;)        {            if(start ==end)            {                if(A[end]<target)return end+1;                else return end;            }            index=(start+end)/2;            if(A[index]<target)            {                start = index+1;            }            else if(A[index]>target){                end =index;            }            else{                return index;            }        }            }}

 

0 0
原创粉丝点击