如何在数组中获取公共值(Java)?

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

How to get the common values in an array (Java)?

问题

public class TwoLists {

    static void arrs() {
        int[] list1 = {1, 6, 2, 1, 4, 1, 2, 1, 8};
        int[] list2 = {1, 2, 1};
        
        for (int i = 0; i < list1.length - 1; i++) {
            for (int o = i + 3; o < list1.length; o++) {
                for (int out1 = list1[i]; out1 == list1[o]; out1++) {
                    System.out.print(out1);
                }
            }
        }
    }

    public static void main(String[] args) {
        arrs();
    }
}
英文:

I want to get the common values of list1 and compare it to list2. I got an output of 11121 instead of 121. How can I resolve this?

Here's my code:

public class TwoLists {

    static void arrs() {
	    int[] list1 = {1, 6, 2, 1, 4, 1, 2, 1, 8};
	    int[] list2 = {1, 2, 1};
	
    	for(int i = 0; i &lt; list1.length-1; i++)
		{
			for(int o = i+3; o &lt; list1.length; o++)
    		{
	    		for(int out1 = list1[i]; out1 == list1[o]; out1++)
		    	{
			    	System.out.print(out1);
				    }
			    }
		    }
	    }


    public static void main(String[] args)
    {
	    arrs();
    }

}

答案1

得分: 0

尝试以下操作:

  • 使用 Set<Integer> 记录已找到的值。
  • 然后使用嵌套数组遍历每个数组,从开始到结束。
  • 在外部循环中,检查 set.contains() 是否包含当前值。
  • 如果是,继续外部循环。
  • 否则,比较内部和外部列表的值。
  • 当找到匹配时,打印该值,添加到集合中,然后跳出内部循环。
  • 继续外部循环中的下一个值。

还有其他更快的方法,只使用集合,但这可以作为一个开始。

英文:

Try the following:

  • Use a Set&lt;Integer&gt; to record those already found.
  • then use a nested array going from start to finish for each array
  • in the outer loop, see if set.contains() the current value.
  • if so, continue outer loop.
  • otherwise, compare inner and outer list values.
  • when a match is found, print it, add to the set, and then break out of the inner loop.
  • continue next value in outer loop.

There are other, faster ways using just sets exclusively but this would serve as a start.

huangapple
  • 本文由 发表于 2020年10月3日 07:17:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/64179233.html
匿名

发表评论

匿名网友

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

确定