我有一个数字x=27
和值数组int[] y=[15,20,25,30,35,40,45]
。Java:将值与数组进行比较;获取前3个数字大于值
如何才能比较两个以获得大于x的数组中的前3个数字?
我想一个for循环需要在这里使用,但我是一个初学者,所以这是超越我。
我有一个数字x=27
和值数组int[] y=[15,20,25,30,35,40,45]
。Java:将值与数组进行比较;获取前3个数字大于值
如何才能比较两个以获得大于x的数组中的前3个数字?
我想一个for循环需要在这里使用,但我是一个初学者,所以这是超越我。
有使用数组一个有效的解决方案:
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`.
我想他明确提到他是一个初学者 –
事实上,这个答案仅仅是使用Java库中的标准(因此是有据可查的)函数。 – Bathsheba
试试这个:
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]+" ");
}
}
输出:
迷人大家如何坚持,基于流以循环......,我们有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);
考虑使问题更简单第一:写东西挑从大于x的数组中取出第一个数字。而且你错过了所有最重要的标准:数组是否被排序? – Bathsheba
是你的数组进行排序?或者你得到的任何随机数组(未排序)? –
欢迎来到SO!预计您会首先投入最少的努力,然后在遇到困难时寻求帮助。否则,这里的人会做的不仅仅是帮助,他们会为你解决问题!你的问题目前提出的方式,你不可能在这里得到很多帮助,对不起。 – Thomas