我们如何在时间〜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;
}
我们可以加快一点吗?!
答案 0 :(得分:3)
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));
}
答案 1 :(得分:1)
想法是计算出现次数,并将其存储在treeMap中。 由于treeMap已排序,我们可以找到不重复的最后一个(最大)数字(值为1)
//tree map is sorted... so the idea is to find the last item with value = 1
TreeMap<Integer,Integer> occurrence = new TreeMap<>();
//tabulate the number of occurrence of each key
//O(2N)
Stream.of(array).forEach( key ->
occurance.compute(key, (k, v) -> v == null ? 1 : v + 1));
//now that we have the treeMap with the number of occurrence,
//we can find the last non-repeated value.
while(!occurance.isEmpty()){
//iterate from the back up
Map.Entry<Integer,Integer> le = occurance.pollLastEntry(); //or var if JAVA10
if (le.getValue==1) return le.getKey();
}
//no unique numbers found
return Integer.MIN_VALUE;
答案 2 :(得分:0)
您可以使用Radix sort按降序对数组进行排序,然后循环遍历并查看currentIndex == currentIndex + 1
。
如果我没有误会,并且仍然优于实际的O(n*x)
,那么这将使O(n)
的最大复杂度与O(n^2)
基本相同。重新使用