The question is this:
You are given two integer arrays nums1 and nums2 sorted in ascending order and an integer k.
Define a pair (u, v) which consists of one element from the first array and one element from the second array.
Return the k pairs (u1, v1), (u2, v2), ..., (uk, vk) with the smallest sums.
My first idea was to find all the sums, and then add it to a minheap, but the time complexity for that is very large I think O(n^2logn).
I can't understand how to optimize the solution to make it faster.
Here is my code for going through all iterations of possible sums then adding them to a min heap. I was wondering how to optimize this code to make it run in O(nlogn).
public List<List<Integer>> kSmallestPairs(int[] nums1, int[] nums2, int k) {
HashMap<ArrayList<Integer>, Integer> all_values = new HashMap<ArrayList<Integer>, Integer>();
PriorityQueue<Map.Entry<ArrayList<Integer>, Integer>> k_pairs = new PriorityQueue<Map.Entry<ArrayList<Integer>, Integer>>(
(a,b) -> b.getValue().compareTo(a.getValue())
);
for(int i = 0; i < nums1.length; i++){
for(int j = 0; j < nums2.length; j++){
ArrayList<Integer> temp = new ArrayList<Integer>();
temp.add(i);
temp.add(j);
all_values.put(temp, nums1[i] + nums2[j]);
}
}
for(Map.Entry<ArrayList<Integer>, Integer> o : all_values.entrySet()){
k_pairs.offer(o);
if(k_pairs.size() > k){
k_pairs.poll();
}
}
List<List<Integer>> final_all_k = new ArrayList<List<Integer>>();
while(k_pairs.size() > 0){
List<Integer> temp = k_pairs.poll().getKey();
int temp_index1 = nums1[temp.get(0)];
int temp_index2 = nums2[temp.get(1)];
temp.clear();
temp.add(temp_index1);
temp.add(temp_index2);
final_all_k.add(temp);
}
return final_all_k;
}