Java 如何计算数组中的负数?
在黑客等级问题中,我想计算负数。如果计数大于整数k,则必须打印“否”。否则为“是”。我得到运行时错误。有没有办法数得更快 我的密码是Java 如何计算数组中的负数?,java,Java,在黑客等级问题中,我想计算负数。如果计数大于整数k,则必须打印“否”。否则为“是”。我得到运行时错误。有没有办法数得更快 我的密码是 public class Solution { public static void main(String args[]) { Scanner s = new Scanner(System.in); int t = s.nextInt(); for (int l = 0; l < t; l++)
public class Solution {
public static void main(String args[]) {
Scanner s = new Scanner(System.in);
int t = s.nextInt();
for (int l = 0; l < t; l++) {
int count = 0;
int k = s.nextInt();
int n = s.nextInt();
ArrayList<Integer> al =new ArrayList();
for (int i = 0; i < n; i++) {
al.add(s.nextInt());
}
Collections.sort(al);
for (int c : al) {
if (c <= 0) {
count += 1;
} else
break;
}
if ((count >= k) || (count == k)) {
System.out.println("NO");
} else {
System.out.println("YES");
}
}
}
}
公共类解决方案{
公共静态void main(字符串参数[]){
扫描仪s=新的扫描仪(System.in);
int t=s.nextInt();
对于(int l=0;l
排序ArrayList
为O(n log n)。使用计数器对ArrayList
进行单次遍历为O(n)。不排序,不存储其他临时变量,如果可以停止使用扫描仪读取输入,请在到达k
时退出:
for (int i = 0; i < n; i++) {
if (s.nextInt() < 0) {
counter++;
}
if (counter > k) {
System.out.println("NO");
return;
}
}
System.out.println("YES");
for(int i=0;ik){
系统输出打印项次(“否”);
返回;
}
}
System.out.println(“是”);
只需在列表上迭代,检查当前数字是否小于零,这样您将得到一个负数。每次这个事实为真时,增加您的计数。简单易行!这也不慢,而且是处理此问题的正常方法。如果您可能有数万亿个数字,并且您也知道集合的确切大小,则y您可以将集合划分为单独的部分(关键字“divide and Conquer”)。然后在自己的线程中对每个部分执行此迭代
吻-保持简单愚蠢
int count = 0;
Collection <Integer> s = null;
for(Integer i : s) {
if(i < 0)
count++;
if(count > k)
System.exit(-1);
}
int count=0;
集合s=null;
for(整数i:s){
if(i<0)
计数++;
如果(计数>k)
系统退出(-1);
}
什么样的错误?你应该先写正确的代码,然后考虑优化。如果你的代码真的工作正常,你只需要一些指针来加快速度,然后考虑把这个问题移到我们的姐妹站点,使用<代码> > <代码>的目的是不必与<代码> ==< /代码> ASWEL进行比较。l、 只需使用if(count>=k)
而不是if((count>=k)| |(count==k))
运行时错误…只是运行时错误..这是唯一优化的解决方案。