j**********m 发帖数: 51 | 1 A non-empty zero-indexed array A consisting of N integers is given.
A pair of integers (P, Q) is calledK-complementary in array A if 0 ≤ P, Q <
N and A[P] + A[Q] = K.
For example, consider array A such that:
A[0] = 1 A[1] = 8 A[2]= -3
A[3] = 0 A[4] = 1 A[5]= 3
A[6] = -2 A[7] = 4 A[8]= 5
The following pairs are 6-complementary in array A: (0,8), (1,6), (4,8), (5,
5), (6,1), (8,0), (8,4).
For instance, the pair (4,8) is 6-complementary because A[4] + A[8] = 1 + 5
= 6.
Write a function:
class Solution { public int solution(int K, int[] A); }
that, given an integer K and a non-empty zero-indexed array A consisting of
N integers, returns the number of K-complementary pairs in array A.
For example, given K = 6 and array A such that:
A[0] = 1 A[1] = 8 A[2]= -3
A[3] = 0 A[4] = 1 A[5]= 3
A[6] = -2 A[7] = 4 A[8]= 5
the function should return 7, as explained above.
Assume that:
N is an integer within the range [1..50,000];
K is an integer within the range [−2,147,483,648..2,147,483,647];
each element of array A is an integer within the range [−2,147,483,648
..2,147,483,647].
Complexity:
expected worst-case time complexity is O(N*log(N));
expected worst-case space complexity is O(N), beyond input storage (not
counting the storage required for input arguments).
Elements of input arrays can be modified.
在网上看到的这题,和leetcode的two sum有点像,可是有重复元素, 而且要输出所有
这样的pair,我想不出除了O(N^2)的算法。 | h*****7 发帖数: 60 | 2 1. 排序: 还是用两头夹的方法 不要去重 每搜到一对(a,b) 就算两次 算到a*2 ==
target的算一次
2. hash: key为值 value为当前出现次数 traverse一遍 查(target-当前值)在不在
hash 在就加上当前出现次数*2 到(当前值*2==target) 的时候就+1 | j**********m 发帖数: 51 | 3 public static int twoSum(int[] A, int k){
HashMap map = new HashMap();
int count = 0;
for(int i = 0; i < A.length; i++){
if(!map.containsKey(A[i])){
map.put(A[i], 0);
}
map.put(A[i], map.get(A[i]) + 1);
}
for(int i = 0; i < A.length; i++){
if(map.get(k - A[i]) != null && map.get(k - A[i]) > 0){
if(A[i] == k - A[i]){
count += 1;
map.put(A[i], map.get(A[i]) - 1);
}
else{
count += 2 * map.get(A[i]) * map.get(k - A[i]);
map.put(A[i], 0);
map.put(k - A[i], 0);
}
}
}
return count;
}
谢谢,这个是用hashmap的算法,之前老想着要输出所有的pair的index,所以怎么都想
不出来。
如果排序再两头夹的话,像 {1, 1, 5, 5} k = 6的时候,index i = 0, j = 3, 这时
候该怎么办呢,因为(0,3),(3,0),(1,3),(3,1),(1,2),(2,1),(0,2),(2,0)都要算啊。 | h*****7 发帖数: 60 | 4 对我忽略了 这样如果再前后找的话worst case是N^2
可以hash value and list of indices of the value,排序,traverse的时候去重就
好了,一旦找到就是加上map[a]和map[b]的所有permutation
【在 j**********m 的大作中提到】 : public static int twoSum(int[] A, int k){ : HashMap map = new HashMap(); : int count = 0; : for(int i = 0; i < A.length; i++){ : if(!map.containsKey(A[i])){ : map.put(A[i], 0); : } : map.put(A[i], map.get(A[i]) + 1); : } : for(int i = 0; i < A.length; i++){
|
|