使用时间~O(N)在数组中查找最大不可重复值 [英] Find max non-repeatable value in the array with a time ~O(N)

查看:119
本文介绍了使用时间~O(N)在数组中查找最大不可重复值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How we could find max non-repeatable value in the array with a time ~O(N)

我试图在很长一段时间内完成它,但是我仅发现~O(2N):

I was trying to do it during huge time, but I found only ~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;

}

我们可以加快一点吗?!

Could we do it a little bit faster?!

推荐答案

    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);

在此您将每个数字映射到数组中的数字。

Here you map each number to a number of times it present in the array.

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

In this case complexity is O(n).

并且只有整数可能是最快的实现

And just out of integer possible the fastest implementation possible

// 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));
}

这篇关于使用时间~O(N)在数组中查找最大不可重复值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆