我们如何在~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/