寻找两个数组的交集

huangapple 未分类评论47阅读模式
英文:

Find the intersection between using two array

问题

  1. 我编写了Java代码来找到两个数组之间的交集
  2. package CaseStudy;
  3. public class Findintersection {
  4. public static void main(String[] args) {
  5. int[] series1 = {1, 2, 3, 4, 5};
  6. int[] series2 = {3, 4, 5, 6, 7};
  7. for (int i = 0; i < series1.length; i++) {
  8. int x = series1[i];
  9. System.out.println(x + " ");
  10. }
  11. for (int j = 0; j < series2.length; j++) {
  12. int y = series2[j];
  13. System.out.println(y + " ");
  14. }
  15. }
  16. }
  17. 我使用for循环生成了各个值但是我无法使用XY变量来比较数据
  18. 我尝试使用IF条件来比较这些值
  19. if (x==y)
  20. {
  21. System.out.println(x + " ");
  22. }
  23. 在比较过程中要么X不可用要么Y不可用
英文:

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

  1. package CaseStudy;
  2. public class Findintersection {
  3. public static void main(String[] args) {
  4. int[] series1 = {1, 2, 3, 4, 5};
  5. int[] series2 = {3, 4, 5, 6, 7};
  6. for (int i = 0; i &lt; series1.length; i++) {
  7. int x = series1[i];
  8. System.out.println(x + &quot; &quot;);
  9. }
  10. for (int j = 0; j &lt; series2.length; j++) {
  11. int y = series2[j];
  12. System.out.println(y + &quot; &quot;);
  13. }
  14. }
  15. }

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.

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

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

答案1

得分: 3

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

  1. for (int i = 0; i < series1.length; i++) {
  2. int x = series1[i];
  3. for (int j = 0; j < series2.length; j++) {
  4. int y = series2[j];
  5. if(x == y)
  6. System.out.format("%d : (%d, %d)%n", x, i, j);
  7. }
  8. }

输出结果:

  1. 3 : (2, 0)
  2. 4 : (3, 1)
  3. 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.

  1. for (int i = 0; i &lt; series1.length; i++) {
  2. int x = series1[i];
  3. for (int j = 0; j &lt; series2.length; j++) {
  4. int y = series2[j];
  5. if(x == y)
  6. System.out.format(&quot;%d : (%d, %d)%n&quot;, x, i, j);
  7. }
  8. }

Output:

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

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

发表评论

匿名网友

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

确定