题解 | #牛群的位置排序#

牛群的位置排序

https://www.nowcoder.com/practice/87c81fa27b9a45c49ed56650dfa6f51b

所用知识

二分查找

所用语言

Java

解题思路

定义左指针,右指针,计算中间值,确认向前或向后查找

完整代码

public int searchInsert (int[] labels, int target) {
    // write code here
    int n=labels.length;
    int left =0;
    int right =n-1;
    while(left<=right){
        int mid = (right+left)/2;
        if(labels[mid]<target){
            left=mid+1;
        }else if(labels[mid]>target){
            right=mid-1;
        }else{
            return mid;
        }
    }
    return left;
}
#牛群的位置排序#
全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务