问题描述
由于正非负整数数组:A1,A2,...,AN。如何找到一个整数对的Au,平均(1≤U&所述; V≤N)。使得(Au和AV)是尽可能的大
例:设N = 4和阵列[2 4 8 10]。这里的答案是8
说明
2和4 = 0
2和8 = 0
2,10 = 2
4和8 = 0
4和10 = 0
8和10 = 8
如何做到这一点如果N可以高达10 ^ 5。我有O(N ^ 2)solution.But它的效率不高。
code:
的for(int i = 0;我n种;我++){
为(诠释J = i + 1的; J&n种; J ++){
如果(ARR [1] - 放大器;常用3 [J] GT; ANS)
{
ANS = ARR [1] - 安培; ARR [J]。
}
}
}
- 降序排列的数组。
- 取前两个数字。如果他们都是连续的两个大国的2(比如说2 ^ k和2 ^(K + 1),那么你就可以删除小于2 ^请在所有元素。 之间
- 从剩余的元素,扣2 ^ķ。
- 重复步骤2和3,直到元件的阵列中的数是2
请注意:如果您发现只有最大的因素是2 ^ k和2 ^(K + 1)和第二大要素之间小于2 ^ K,那么你将不会删除任何元素,但只是减去2 ^ķ从最大的元素
此外,确定其中的一个元素在于系列{1,2,4,8,16,...}可为O完成(日志(日志(MAX)))的时间,其中MAX是最大数阵列
Given an array of n non-negative integers: A1, A2, …, AN. How to find a pair of integers Au, Av (1 ≤ u < v ≤ N) such that (Au and Av) is as large as possible.
Example : Let N=4 and array be [2 4 8 10] .Here answer is 8
Explanation
2 and 4 = 0
2 and 8 = 0
2 and 10 = 2
4 and 8 = 0
4 and 10 = 0
8 and 10 = 8
How to do it if N can go upto 10^5.I have O(N^2) solution.But its not efficient
Code :
for(int i=0;i<n;i++){
for(int j=i+1;j<n;j++){
if(arr[i] & arr[j] > ans)
{
ans=arr[i] & arr[j];
}
}
}
- Sort the array in descending order.
- Take the first two numbers. If they are both between two consecutive powers of 2 (say 2^k and 2^(k+1), then you can remove all elements that are less than 2^k.
- From the remaining elements, subtract 2^k.
- Repeat steps 2 and 3 until the number of elements in the array is 2.
Note: If you find that only the largest element is between 2^k and 2^(k+1) and the second largest element is less than 2^k, then you will not remove any element, but just subtract 2^k from the largest element.
Also, determining where an element lies in the series {1, 2, 4, 8, 16, ...} can be done in O(log(log(MAX))) time where MAX is the largest number in the array.
这篇关于最大限度地提高了与的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!