如何在数组列表中查找相同整数的倍数?

发布于 2024-08-30 19:36:11 字数 296 浏览 5 评论 0原文

我的问题如下。我有一个整数数组列表。 arraylist 包含 5 个整数,例如 [5,5,3,3,9] 或可能 [2,2,2,2,7]。许多数组列表都有重复的值,我不确定如何计算每个值存在多少个。

问题是如何在数组列表中找到重复值并计算该特定重复值的数量。在第一个示例 [5,5,3,3,9] 中,有 2 个 5 和 2 个 3。 [2,2,2,2,7] 的第二个例子只有 4 个 2。我希望找到的结果信息是是否存在重复项,其中有多少个以及重复的特定整数。

我不太确定如何在 java 中执行此操作。

任何帮助将不胜感激。谢谢。

My problem is as follows. I have an arraylist of integers. The arraylist contains 5 ints e.g[5,5,3,3,9] or perhaps [2,2,2,2,7]. Many of the arraylists have duplicate values and i'm unsure how to count how many of each of the values exist.

The problem is how to find the duplicate values in the arraylist and count how many of that particular duplicate there are. In the first example [5,5,3,3,9] there are 2 5's and 2 3's. The second example of [2,2,2,2,7] would be only 4 2's. The resulting information i wish to find is if there are any duplicates how many of them there are and what specific integer has been duplicated.

I'm not too sure how to do this in java.

Any help would be much appreciated. Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

私野 2024-09-06 19:36:11

对我来说,最直接的答案是使用Collections.Frequency方法。大致如下:

// Example ArrayList with Integer values
ArrayList<Integer> intList = new ArrayList<Integer>();
intList.add(2);
intList.add(2);
intList.add(2);
intList.add(2);
intList.add(7);

Set<Integer> noDupes = new HashSet<Integer>();
noDupes.addAll(intList); // Remove duplicates

for (Integer i : noDupes) {
    int occurrences = Collections.frequency(intList, i);
    System.out.println(i + " occurs " + occurrences + " times.");
}

如果您愿意,您可以将每个 Integer 与其出现次数进行映射:

Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (Integer i : noDupes) {
    map.put(i, Collections.frequency(intList, i));
}

To me, the most straightforward answer, would be using the Collections.frequency method. Something along the lines of this:

// Example ArrayList with Integer values
ArrayList<Integer> intList = new ArrayList<Integer>();
intList.add(2);
intList.add(2);
intList.add(2);
intList.add(2);
intList.add(7);

Set<Integer> noDupes = new HashSet<Integer>();
noDupes.addAll(intList); // Remove duplicates

for (Integer i : noDupes) {
    int occurrences = Collections.frequency(intList, i);
    System.out.println(i + " occurs " + occurrences + " times.");
}

If you want to, you could map each Integer with its number of occurrences:

Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (Integer i : noDupes) {
    map.put(i, Collections.frequency(intList, i));
}
心奴独伤 2024-09-06 19:36:11

我想到了两种算法。

对它进行排序(Collections.sort)。然后通过迭代轻松找到欺骗者。

通过在 Map 中保存计数(或 Map 对于可变计数)进行迭代。这个样子有点丑啊

不管怎样,编码应该是一个有启发性的练习。我建议两者都做,然后进行比较。

Two algorithms spring to mind.

Sort it (Collections.sort). Then iterate through easily finding dupes.

Iterate through keeping count in a Map<Integer,Integer> (or Map<Integer,AtomicInteger> for a mutable count). A bit ugly this way.

Either way, coding it should be an instructive exercise. I suggest doing both, and comparing.

回忆追雨的时光 2024-09-06 19:36:11

这是我在 @Tom 的答案的评论中描述的具体实现,经过测试:

package playground.tests;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

import junit.framework.TestCase;

public class DupeCounterTest extends TestCase {

    public void testCountDupes() throws Exception {
        int[] array = new int[] { 5, 5, 3, 3, 9 };
        assertEquals("{3=2, 5=2}", countDupes(array).toString());
    }

    private Map<Integer, AtomicInteger> countDupes(int[] array) {
        Map<Integer, AtomicInteger> map = new HashMap<Integer, AtomicInteger>();
        // first create an entry in the map for every value in the array
        for (int i : array)
            map.put(i, new AtomicInteger());
        // now count all occurrences
        for (int i : array)
            map.get(i).addAndGet(1);
        // now get rid of those where no duplicate exists
        HashSet<Integer> discards = new HashSet<Integer>();
        for (Integer i : map.keySet())
            if (map.get(i).get() == 1)
                discards.add(i);
        for (Integer i : discards) 
            map.remove(i);
        return map;
    }

}

Here is a concrete implementation, with test, of what I described in comments to @Tom's answer:

package playground.tests;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

import junit.framework.TestCase;

public class DupeCounterTest extends TestCase {

    public void testCountDupes() throws Exception {
        int[] array = new int[] { 5, 5, 3, 3, 9 };
        assertEquals("{3=2, 5=2}", countDupes(array).toString());
    }

    private Map<Integer, AtomicInteger> countDupes(int[] array) {
        Map<Integer, AtomicInteger> map = new HashMap<Integer, AtomicInteger>();
        // first create an entry in the map for every value in the array
        for (int i : array)
            map.put(i, new AtomicInteger());
        // now count all occurrences
        for (int i : array)
            map.get(i).addAndGet(1);
        // now get rid of those where no duplicate exists
        HashSet<Integer> discards = new HashSet<Integer>();
        for (Integer i : map.keySet())
            if (map.get(i).get() == 1)
                discards.add(i);
        for (Integer i : discards) 
            map.remove(i);
        return map;
    }

}
疯到世界奔溃 2024-09-06 19:36:11

除了数组列表之外,还使用 ​​Hashmap 集合,其中

  • Hashmap 键是唯一的数组 int 值,
  • 键的 Hashmap 值是遇到的每个值的计数。

遍历数组列表,将这些值收集到哈希图中,当先前的键不存在时添加一个新项目,并将已存在的键的值加 1。然后迭代 Hashmap 并打印出值 > 的所有键。 1.

Use a Hashmap collection in addition to the array list where

  • the Hashmap key is the unique array int value and
  • the Hashmap value to the key is the count of each value encountered.

Walk your array list collecting these values into the hashmap adding a new item when a previous key does not exist and incrementing by 1 the values of keys that do already exist. Then iterate over the Hashmap and print out any keys where the value is > 1.

愚人国度 2024-09-06 19:36:11

您可以浏览 List 并将它们放入带有计数的 Map 中。然后很容易找出哪一个是重复的。

You can go through the List and put them in a Map with the count. Then it is easy figure out which one is duplicated.

且行且努力 2024-09-06 19:36:11

为了更清晰地抽象您正在做的事情,您可以使用 Multiset 数据结构,来自 guava/ Google 集合。您甚至可能会发现您宁愿使用它而不是 List,具体取决于您使用它做什么(如果您不需要列表的确定性排序)。您可以这样使用它:

Multiset<Integer> multiset = HashMultiset.create(list);
int count = multiset.count(3); // gets the number of 3s that were in the list

就上面的幕后操作而言,它几乎完全等同于基于您的列表构建 Map 的建议。

For a cleaner abstraction of what you're doing, you could use the Multiset data structure from guava/google-collections. You may even find you'd rather use it than a List, depending on what you're doing with it (if you don't need the deterministic ordering of a list). You'd use it like this:

Multiset<Integer> multiset = HashMultiset.create(list);
int count = multiset.count(3); // gets the number of 3s that were in the list

In terms of what the above is doing under the covers, it's almost exactly equivalent to the suggestion of building a Map<Integer,AtomicInteger> based on your list.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文