【问题标题】:How to count the number of equal values in two arrays? [closed]如何计算两个数组中相等值的数量? [关闭]
【发布时间】:2013-03-27 18:29:48
【问题描述】:

例如:

int[] a = [0,1,2,3,4,5];
int[] b = [3,4,5,6,7,8];

count = 3;

数组不必是连续的数字。 我如何获得这些数组之间相等的值的数量?

编辑:所以我尝试了以下操作:

List<int[]> w = Arrays.asList(winning);
List<int[]> s = Arrays.asList(F1Select);            
w.retainAll(s);
int equalNums = w.size();

但我在 retainAll 行收到以下错误:

Exception in thread "AWT-EventQueue-0" java.lang.UnsupportedOperationException
    at java.util.AbstractList.remove(Unknown Source)
    at java.util.AbstractList$Itr.remove(Unknown Source)
    at java.util.AbstractCollection.retainAll(Unknown Source)

【问题讨论】:

  • 你试过什么?基本逻辑是跟踪您已经访问过的那些。
  • 我建议你先对数组进行排序,然后就很容易了
  • 使用嵌套循环,值在一个数组中是唯一的还是重复的?
  • 另一个重要方面:数组中的值是否唯一?
  • @SotiriosDelimanolis - The basic logic is to keep track of the ones you've already visited. 是什么意思?

标签: java arrays


【解决方案1】:

您可以只转换为列表,然后使用 retainAll 找到交集。

List<Integer> aList =  Arrays.asList(a);
List<Integer> bList =  Arrays.asList(b);
aList.retainAll(bList);
return aList.size();

aList 将只包含也在 bList 中的项目,aList 的大小让您知道计数。

如果您只想要唯一值,您可以将数组转换为 Set 并执行相同的操作。

【讨论】:

  • 我正在使用 Eclipse,它告诉我 List 而不是 List
【解决方案2】:

Try this :

 Integer[] a = new Integer[]{0, 1, 2, 3, 4, 5};
 Integer[] b = new Integer[]{3, 4, 5, 6, 7, 8};

  List<Integer> list1 = Arrays.asList(a);
  Set<Integer> commonSet = new TreeSet<Integer>();
     for (Integer i : b) {
         if (list1.contains(i)) {
           commonSet.add(i);
            }
        }

        System.out.println(commonSet.size());

【讨论】:

    【解决方案3】:

    如果允许在计算期间使用O(m + n) 额外空间,则可以为每个数组保留一个 HashMap。键是每个数组元素,值是它出现的次数。计算出每个数字出现的频率后,您就可以将问题简化为比较两张地图。

    只要您在两个映射中都有一个键,那么您就有一个在两个数组中都存在的数字。这些值可以让您决定数字在两个数组中出现的次数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-03-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-15
      • 1970-01-01
      相关资源
      最近更新 更多