在java中以有效的方式从数组中返回重复项

时间:2014-06-17 06:57:35

标签: java collections

我想在数组中返回重复项。

int[] strArray = new int[] {1,1, 2, 3, 2, 2, 3};

我使用了以下方法返回重复项。

private static Set<Integer> checkDuplicate(int[] intArray) {
    Set<Integer> values = new HashSet<>();

    for (int i = 0; i < intArray.length - 1; i++) {
        if (intArray[i] == (intArray[i + 1])) {
            values.add(intArray[i]);
        }

        else
            System.out.println("not equal");
    }

    return values;
}

但是通过这种方式,它只检查了连续的价值。这需要大量的比较和耗时。那么还有更好的方法吗?

6 个答案:

答案 0 :(得分:2)

您可以尝试example

import java.util.*;
class Ideone
{
    public static void main (String[] args) throws java.lang.Exception
    {
        int[] strArray = new int[] {1,1, 2, 3, 2, 2, 3, 4, 7, 5, 4};
        Set<Integer> duplicates = checkDuplicate(strArray);
        System.out.printf("Duplicates: %s\n", duplicates);
    }
    private static Set<Integer> checkDuplicate(int[] intArray)
    {
        Set<Integer> duplicates = new HashSet<Integer>();
        Set<Integer> tmp = new HashSet<Integer>();
        for(Integer i: intArray)
        {
            if(!tmp.add(i))
            {
                duplicates.add(i);
            }
        }
        return duplicates;
    }
}

答案 1 :(得分:1)

如果您正在寻找效率 使用它HashMap的{​​{1}},同时迭代O(1) speed中的整数数组,因为它比普通enhanced forloop

稍快一些
forloop

答案 2 :(得分:1)

如果您不想使用散列(HashSet或HashMap),则可以先对数组进行排序。然后,您可以通过检查连续值来查找重复项。总的来说,这种方法的时间复杂度为O(n log n)。

答案 3 :(得分:0)

public static void main(String[] args) {
        int[] arr = { 1, 2, 3, 1, 4, 4, 1, 5 };
        // System.out.println(Arrays.toString(arr));
        List<Integer> l = new ArrayList<Integer>();
        for (int i = 0; i < arr.length; i++) {
            l.add(i, arr[i]);
        }
        // System.out.println(l);
        Set<Integer> set = new HashSet<Integer>();
        for (int j = 0; j < l.size(); j++) {
            if (Collections.frequency(l, l.get(j)) > 1) {
                set.add(l.get(j));
            }
        }

        System.out.println(set);

    }

O/P :
[1, 4]

答案 4 :(得分:0)

扫描您的输入并将每个号码存储在Map<Interger, Integer>中。然后循环遍历Map,并在结果Set

中输入值> 1的所有键

另见:https://stackoverflow.com/a/15217535/461499

答案 5 :(得分:0)

您必须使用Collections.frequency

它只使用equals方法。如果您使用任何集合Map,Set,List使用equals方法来比较两个对象以及Has集合使用的hashCode方法需要更多的处理时间。