寻找两个数组的交集

huangapple go评论84阅读模式
英文:

Find the intersection between using two array

问题

我编写了Java代码来找到两个数组之间的交集

    package CaseStudy;
    
    public class Findintersection {
    
      public static void main(String[] args) {
        int[] series1 = {1, 2, 3, 4, 5};
        int[] series2 = {3, 4, 5, 6, 7};
    
        for (int i = 0; i < series1.length; i++) {
    
          int x = series1[i];
          System.out.println(x + " ");
        }
        for (int j = 0; j < series2.length; j++) {
          int y = series2[j];
          System.out.println(y + " ");
        }
      }
    }

我使用for循环生成了各个值但是我无法使用X和Y变量来比较数据

我尝试使用IF条件来比较这些值

     if (x==y)
    		 {
    			 System.out.println(x + " ");
    		 } 

在比较过程中要么X不可用要么Y不可用
英文:

I have written Java code to find the intersection between two arrays

package CaseStudy;

public class Findintersection {

  public static void main(String[] args) {
    int[] series1 = {1, 2, 3, 4, 5};
    int[] series2 = {3, 4, 5, 6, 7};

    for (int i = 0; i &lt; series1.length; i++) {

      int x = series1[i];
      System.out.println(x + &quot; &quot;);
    }
    for (int j = 0; j &lt; series2.length; j++) {
      int y = series2[j];
      System.out.println(y + &quot; &quot;);
    }
  }
}

I generated the individual values using for loop . But I am not able to use X and Y variable to compare the data.

I tried using IF conditions to compare the values.

 if (x==y);
		 {
			 System.out.println(x + &quot; &quot;);
		 } 

While comparing either X is not available or Y is not available.

答案1

得分: 3

你离答案很近了,你只需要将第二个for循环嵌套在第一个循环内部,这样你就可以将第一个数组中的每个值与第二个数组中的每个值进行比较。

for (int i = 0; i < series1.length; i++) {
  int x = series1[i];

  for (int j = 0; j < series2.length; j++) {
    int y = series2[j];

    if(x == y)
      System.out.format("%d : (%d, %d)%n", x, i, j);
  }
}

输出结果:

3 : (2, 0)
4 : (3, 1)
5 : (4, 2)
英文:

You're close, you just need to nest the 2nd for loop inside the 1st so that you compare each value in the 1st array with every value in the 2nd.

for (int i = 0; i &lt; series1.length; i++) {
  int x = series1[i];

  for (int j = 0; j &lt; series2.length; j++) {
    int y = series2[j];
      
    if(x == y)
      System.out.format(&quot;%d : (%d, %d)%n&quot;, x, i, j);
  }
}

Output:

3 : (2, 0)
4 : (3, 1)
5 : (4, 2)

huangapple
  • 本文由 发表于 2020年4月7日 03:07:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/61067173.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定