LeetCode Problem Link: https://leetcode.com/problems/4sum-ii/description/
Sol:
class Solution {
public int fourSumCount(int[] A, int[] B, int[] C, int[] D) {
Map<Integer, Integer> sumABMap = new HashMap();
for (int i = 0; i < A.length; i++) {
for (int j = 0; j < B.length; j++) {
int sum = A[i] + B[j];
sumABMap.put(sum, sumABMap.getOrDefault(sum, 0) + 1);
}
}
int touples = 0;
for (int i = 0; i < C.length; i++) {
for (int j = 0; j < D.length; j++) {
touples += sumABMap.getOrDefault(-C[i] - D[j], 0);
}
}
return touples;
}
}
Complexity:
O(n^2) time complexity (Compute the sum of AB and CD.)
O(n^2) space complexity (Store the sum of A and B)
Result:
Runtime: 132ms
Beats 98.25% users.
Sol:
class Solution {
public int fourSumCount(int[] A, int[] B, int[] C, int[] D) {
Map<Integer, Integer> sumABMap = new HashMap();
for (int i = 0; i < A.length; i++) {
for (int j = 0; j < B.length; j++) {
int sum = A[i] + B[j];
sumABMap.put(sum, sumABMap.getOrDefault(sum, 0) + 1);
}
}
int touples = 0;
for (int i = 0; i < C.length; i++) {
for (int j = 0; j < D.length; j++) {
touples += sumABMap.getOrDefault(-C[i] - D[j], 0);
}
}
return touples;
}
}
Complexity:
O(n^2) time complexity (Compute the sum of AB and CD.)
O(n^2) space complexity (Store the sum of A and B)
Result:
Runtime: 132ms
Beats 98.25% users.
留言
張貼留言