【发布时间】:2021-10-13 06:51:18
【问题描述】:
我在 Hackerrank 上练习编码,我实现了一个适用于苹果但不适用于橘子的逻辑。我知道为什么。有什么想法吗?
*//int s = start of the house
// int t = end of the house...
// int a = Apple tree location
// int b = Orange tree location
// Integer apples is a list of numbers.
// Integer oranges is a list numbers aswell.
逻辑如下:
如果树的位置指向int a 和int b 加上List<Integer> apples/oranges 的值在s 和t 之间,我们必须将计数器加一。我们对苹果和橙子使用不同的计数器。
public static void countApplesAndOranges(int s, int t, int a, int b, List<Integer> apples, List<Integer> oranges) {
// Write your code here
int applesOnhouse = 0;
int orangeOnhouse = 0;
List<Integer> house = new ArrayList<>();
for(int i = s; s < t; s++){
house.add(i);
}
for(int j = 0; j < apples.size(); j++){
if(house.contains(a + apples.get(j))){
applesOnhouse++;
}
}
for(int z = 0; z < oranges.size(); z++){
if(house.contains(b + oranges.get(z))){
orangeOnhouse++;
}
}
System.out.println(applesOnhouse);
System.out.println(orangeOnhouse);
}
}
我有点初级,我只是不明白为什么它适用于苹果而不适用于橙子。我只想更深入地了解数组操作、列表操作和逻辑。
【问题讨论】:
-
你能给那些变量一个更有意义的名字吗?它们的含义是什么?这几乎与学习如何循环数组一样重要。
-
如果没有一些示例输入以及您对应该产生的结果的期望,我不确定我们能否为您提供帮助。
-
我能想到的唯一原因是 oranges.size() == 0