java - 用时间 ~O(N) 在数组中找到最大不可重复值

标签 java algorithm max equality

我们如何在~O(N) 的时间内找到数组中的最大不可重复值

我花了很长时间尝试这样做,但我发现只有 ~O(2N):

int solution(int[] A) {

    List<Integer> arr = new ArrayList<Integer>();
    Set<Integer> set = new HashSet<Integer>();

    int max = 0;

    for(int i = 0; i < A.length; i++) {

        if(!set.add(A[i])) arr.add(A[i]);

    }

    for(int i = 0; i < A.length; i++) {
        if (max < A[i] && !arr.contains(A[i])) max = A[i];
    }

    return max;

}

我们可以做得更快一点吗?!

最佳答案

    int A[] = {5, 5, 3, 2, 3, 1};
    Map<Integer, Integer> map = new HashMap<>();

    for(int i : A) {
        Integer count = map.get(i);
        // according to the comments
        // map.merge(i, 1, Integer::sum)
        map.put(i, count == null ? 1 : count + 1);
    }

    int max = 0;
    for (Map.Entry<Integer, Integer> e : map.entrySet()) {
        if (e.getValue() == 1 && max < e.getKey()) {
            max = e.getKey();
        }
    }

    System.out.println(max);

在这里,您将每个数字映射到它在数组中出现的次数。

在这种情况下,复杂度为 O(n)。

并且尽可能快地实现可能的整数

// this code for academic purpose only
// it can work only with integers less than
// 2^nextPowerOfTwo(array.lenght) as
// hash collision doesn't resolved
public static int nextPowerOfTwo(int value) {
    value--;
    value |= value >> 1;
    value |= value >> 2;
    value |= value >> 4;
    value |= value >> 8;
    value |= value >> 16;

    return ++value;
}

public static int findMaxUnique(int[] array) {
    final int hashSize = nextPowerOfTwo(array.length);
    final int[] hashArray = new int[hashSize];

    for (int n : array) {
        int hash = n ^ (n >>> 16);
        hash &= hashSize - 1;
        hashArray[hash]++;
    }

    int max = 0;
    for (int n : array) {
        int hash = n ^ (n >>> 16);
        hash &= hashSize - 1;
        if (hashArray[hash] == 1 && max < n) {
            max = n;
        }
    }

    return max;
}

public static void main(String[] args) {
    int[] array = {5, 4, 5, 3, 1, 5, 4, 0};
    System.out.println(findMaxUnique(array));
}

关于java - 用时间 ~O(N) 在数组中找到最大不可重复值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50307498/

相关文章:

java - 为什么 Gradle 只包含我的库中具有项目依赖性的类

c# - 如何实现自动调整大小

javascript - 最小和最大日期

Java,限制BufferedReader读取时间

c++ - 理解 8 皇后拼图的对角搜索

MySQL:为按日期分组的最大值选择相应的行

java - 如何将 Vaadin Valo Theme 更改为 Metro?

java - Talend - 从 1 行生成 n 多行

java - 为什么使用 Collections.binarySearch() 时得到错误答案

ruby - 如何创建一个返回数组中回旋镖总数的函数