繁体   English   中英

比较三胞胎。 打印两个空格分隔的整数,表示 Alice 和 Bob 分别获得的比较点

[英]Compare the triplets. Print two space-separated integers denoting the respective comparison points earned by Alice and Bob

问题有网址链接hackerrankquestion

我写了这段代码:

 import java.io.*; import java.util.*; import java.text.*; import java.math.*; import java.util.regex.*; public class Solution { public static void main(String[] args) { Scanner in = new Scanner(System.in); int a0 = in.nextInt(); int a1 = in.nextInt(); int a2 = in.nextInt(); int b0 = in.nextInt(); int b1 = in.nextInt(); int b2 = in.nextInt(); int[] result = solve(a0, a1, a2, b0, b1, b2); for (int i = 0; i < result.length; i++) { System.out.print(result[i] + (i != result.length - 1 ? " " : "")); } System.out.println(""); } static int[] solve(int a0, int a1, int a2, int b0, int b1, int b2){ // Complete this function int resultA = 0; int resultB = 0; int[] arrA = {a0,a1,a2}; int[] arrB = {b0,b1,b2}; for(int i = 0; i <3; i++){ if (arrA[i] > arrB[i] && arrA[i] - arrB[i] != 0){ resultA++; }else resultB++ ; } int[] array = {resultA, resultB}; return array; } }

没有通过测试。 附上快照。 在此处输入图片说明

然后我操纵结果 B = -1 并欢呼,我通过了测试测试用例通过

只知道我失败的其余测试用例。 在此处输入图片说明

任何见解请为什么这发生在我身上。

我想,我在你的逻辑中发现了错误,就在这里

这是解决方法的正确实现

  static int[] solve(int a0, int a1, int a2, int b0, int b1, int b2){
    // Complete this function
    int resultA = 0;
    int resultB = 0;
    int[] arrA = {a0,a1,a2};
    int[] arrB = {b0,b1,b2};
    for(int i = 0; i <3; i++){
        if (arrA[i] > arrB[i] && arrA[i] - arrB[i] != 0){
            resultA++;
        }else if(arrB[i] > arrA[i] && arrB[i] - arrA[i] != 0){resultB++ ;}
    }
    int[]  array = {resultA, resultB};
    return array;

}

所以发生的事情是,如果 A 和 B 的值相等,那么你也在增加 B,这不是你想要的。

希望这可以帮助!

如果将主函数修改为,此代码可以大大简化,

public static void main(String[] args) {

        Scanner in = new Scanner(System.in);
        int a0 = in.nextInt();
        int a1 = in.nextInt();
        int a2 = in.nextInt();
        int b0 = in.nextInt();
        int b1 = in.nextInt();
        int b2 = in.nextInt();
        int[] result = solve(a0, a1, a2, b0, b1, b2);
        //for (int i = 0; i < result.length; i++) {
          //  System.out.print(result[i] + (i != result.length - 1 ? " " : ""));
        //}
        System.out.println(result[0]+" "+result[1]);//much simplified format


    }
#include <stdio.h>

int main()
{
    int x,y,z,a,b,c,count_a=0,count_b=0;
    scanf("%d%d%d",&a,&b,&c);
    scanf("%d%d%d",&x,&y,&z);

    if(a>x)
    count_a++;
    if(a<x)
    count_b++;
    if(b>y)
    count_a++;
    if(b<y)
    count_b++;
    if(c>z)
    count_a++;
    if(c<z)
    count_b++;
    printf("%d %d",count_a,count_b);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM