从任意两个整数的和中删除数组中的相似元素

我的输入是一个整数假设M,程序必须打印两个整数x和ywhere 的所有组合x + y = M。


让我们将输入作为M = 50和数组元素作为25 20 25 30 15 45 45 5 ,我需要的输出是


5 45,20 30,25 25.

但我的输出是


5 45,5 45,20 30,25,25

如何消除那两次的发生5 45?


我的代码如下


Scanner s = new Scanner(System.in);

int m = s.nextInt();

s.nextLine();

String str = s.nextLine();

StringTokenizer st = new StringTokenizer(str);

int len = st.countTokens();

int[] a = new int[len];

String[] temp = new String[len];

for (int i = 0; i < len; i++)

{

    temp[i] = st.nextToken();

    a[i] = Integer.parseInt(temp[i]);

}

Arrays.sort(a);


for (int i = 0;i < len-1; i++)

{

    for(int j = i + 1; j < len; j++)

    {

        if ((a[i] +a [j]) == m)

            System.out.println(a[i] + " " + a[j]);

    }

}


萧十郎
浏览 123回答 3
3回答

白衣非少年

使用break用于跳过重复数(内环),并检查(a[i] - a[i+1]) == 0和使用continue跳过外环重复数。仅在for循环中包含以下更改,完美运行// Init a new array.for(int i=0;i<len-1;i++){&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; if((a[i] - a[i+1]) == 0)&nbsp; &nbsp; &nbsp; &nbsp;continue;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;// for skipping repeated number in outer loop&nbsp;&nbsp; &nbsp; for(int j=i+1;j<len;j++)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; if((a[i]+a[j])==m ) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println(a[i]+" "+a[j]);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;// for skipping repeated number in inner loop&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; else if(a[i] == m/2){&nbsp; &nbsp; &nbsp; &nbsp; System.out.println(a[i]+" "+a[i]);&nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp;}输入25 ,20, 25 ,30, 15, 45, 45, 5输出5 4520 3025 25输入5 ,5 ,45, 45, 45输出5 45
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java