Java:将值与数组进行比较;使前3个数字更大



我有一个数字 x=27和一个值 int[] y=[15,20,25,30,35,40,45]

如何比较两者,以便从数组中获取大于x的前3个数字?

我猜我需要在这里使用循环,但我是初学者,所以这超出了我。

使用数组有一个工作解决方案:

public class Main {
    public static void main(String[] args) {
        int x = 27;
        int[] y = {15, 20, 25, 30, 35, 40, 45};
        int[] result = new int[3];
        int z = 0;
        for(int i = 0; i < y.length; i++) {
            if(y[i] > x && z < 3) {
                result[z] = y[i];
                z++;
            }
        }
        System.out.println(result[0] + " " + result[1] + " " + result[2]); //Print 30 35 40
    }
}

如果对数组进行排序并且不包含重复项(如给出的示例中,您可以使用二进制搜索快速获得此结果:

int pos = java.util.Arrays.binarySearch(
    y,
    0/*inclusive as per function spec*/,
    y.length/*exlusive as per function spec*/,
    x 
);
if (pos >= 0){
    // x is found at position 'pos', but we want elements greater than this.
    ++pos;
} else {
    int i = -pos - 1; // this is where x would be inserted to preserve sortedness
    pos = i + 1;
}
// ToDo - your elements are at `pos`, `pos + 1`, and `pos + 2`,
// subject to your not running over the end of the array `y`.

尝试以下:

int[] y={15,30,29,30,35,40,45};
    int x=27;
    for(int i = 0,index = 3; i < y.length; i++){
        if(i < index && y[i] > x){
            System.out.print(y[i]+" ");
        }
    }

输出:

30 29

令人着迷的每个人都坚持循环...基于流,我们毕竟有2016年:

    int[] y = {15, 20, 25, 30, 35, 40, 45};
    int x = 17;
    IntStream.of(y).filter(v -> v > x).limit(3).forEach(System.out::println);

最新更新