虾皮8.23笔试第一道编程题有比较好的解法吗

import java.util.*;

public class Main{
    public static void main(String[] args){
        int[] array = new int[]{1,2,3,3,3,3,4};
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int[] res = minAndmax(array,n);
        System.out.println(res[0]+","+res[1]);
    }
    public static int[] minAndmax(int[] array,int n){
        int[] res = new int[]{-1,-1};
        int left = 0;
        int right = array.length-1;
        while(left<right){
            int mid = left+(right-left)/2;
            if(n==array[mid]){
                left = mid;
            }else if(n<array[mid]){
                right = mid-1;
            }else {
                left = mid+1;
            }
            if(left==right-1){
                res[1]=left;
                break;
            }
            if(left==right && n==array[left]){
                res[0]=left;
                res[1]=right;
                return res;
            }
        }
        right = left;
        left = 0;
        while(left<right){
            int mid = left+(right-left)/2;
            if(n==array[mid]){
                right=mid;
            }else if(n>array[mid]){
                left=mid+1;
            }else {
                right=mid-1;
            }
        }
        if(n==array[left]){
            res[0]=left;
        }
        return res;
    }
}
#虾皮笔试##Shopee##笔试题目#
全部评论
写了好久 被边界条件弄得很烦
点赞 回复 分享
发布于 2021-08-23 16:47

相关推荐

喜欢吃蛋糕仰泳鲈鱼是我的神:字节可以找个hr 给你挂了,再放池子捞
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务