美文网首页
60搜索插入位置

60搜索插入位置

作者: shenlong77 | 来源:发表于2017-10-26 22:15 被阅读0次

给定一个排序数组和一个目标值,如果在数组中找到目标值则返回索引。如果没有,返回到它将会被按顺序插入的位置。
你可以假设在数组中无重复元素。

[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 {
    /*
     * @param A: an integer sorted array
     * @param target: an integer to be inserted
     * @return: An integer
     */
    public int searchInsert(int[] A, int target) {
        // write your code here
        if(A==null){
            return -1;
        }
        if(A.length==0||A[0]>target){
            return 0;
        }
        if(A[A.length-1]<target){
            return A.length;
        }
        int startIndex=0;
        int endIndex=A.length-1;
        int middleIndex;
        while(true){
            middleIndex=(startIndex+endIndex)/2;
            if(A[middleIndex]==target){
                return middleIndex;
            }
            //最后肯定是剩两个数,这两个数左边的都比target小,右边的都比target大
            if(startIndex>=endIndex){
                if(target>A[startIndex]){
                    return startIndex+1;
                }
                else{
                    return startIndex;
                }
            }else{
                if(target>A[middleIndex]){
                    startIndex=middleIndex+1;
                }else{
                    endIndex=middleIndex-1;
                }
            }
        }
    }
}

相关文章

  • 60搜索插入位置

    给定一个排序数组和一个目标值,如果在数组中找到目标值则返回索引。如果没有,返回到它将会被按顺序插入的位置。你可以假...

  • 60. 搜索插入位置

    60. 搜索插入位置 描述 笔记 数据 评测 给定一个排序数组和一个目标值,如果在数组中找到目标值则返回索引。如果...

  • 60. 搜索插入位置

    给定一个排序数组和一个目标值,如果在数组中找到目标值则返回索引。如果没有,返回到它将会被按顺序插入的位置。 你可以...

  • 搜索插入位置

    给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的...

  • 搜索插入位置

    题目描述 给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按...

  • 搜索插入位置

    给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的...

  • 搜索插入位置

  • 搜索插入位置

    搜索插入位置 给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会...

  • 搜索插入位置

    for i in range(len(nums)): if target <= nums[i]: ...

  • 搜索插入位置

    题目需求 给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按...

网友评论

      本文标题:60搜索插入位置

      本文链接:https://www.haomeiwen.com/subject/bahlpxtx.html