LeetCode 454. 4Sum II

来源:互联网 发布:三枪内裤怎么样 知乎 编辑:程序博客网 时间:2024/06/07 02:32

Description:
Given four lists A, B, C, D of integer values, compute how many tuples (i, j, k, l) there are such that A[i] + B[j] + C[k] + D[l] is zero.

To make problem a bit easier, all A, B, C, D have same length of N where 0 ≤ N ≤ 500. All integers are in the range of -228 to 228 - 1 and the result is guaranteed to be at most 231 - 1.

Example:

Input:A = [ 1, 2]B = [-2,-1]C = [-1, 2]D = [ 0, 2]Output:2Explanation:The two tuples are:1. (0, 0, 0, 1) -> A[0] + B[0] + C[0] + D[1] = 1 + (-2) + (-1) + 2 = 02. (1, 1, 0, 0) -> A[1] + B[1] + C[0] + D[0] = 2 + (-1) + (-1) + 0 = 0

本题思路如下:
题目要求找到满足这样的条件的元组(i,j,k,l):A[i] + B[j] + C[k] + D[l] = 0
可将该条件转化一下,变为:A[i] + B[j] = -C[k] - D[l]
这样转化以后,问题的条件就被转化为了A,B和C,D两部分
接着可以想到使用map来处理这个条件:遍历A和B数组,对于可能的每一个和,像map中进行插入,若已存在该和,则该和对应的次数+1;接着遍历C,D数组,同样,对于每一个可能的和,取该和的负数到map中进行查询,若存在,则找到了使A[i] + B[j] = -C[k] - D[l]条件满足的元组,而元组的个数则是map中该项的值。

代码如下:

class Solution {public:    int fourSumCount(vector<int>& A, vector<int>& B, vector<int>& C, vector<int>& D) {        unordered_map<int, int> map;        int count = 0;        for(auto a: A) {            for(auto b: B) {                map[a + b]++;            }        }        for(auto c: C) {            for(auto d: D) {                auto i = map.find(-c - d);                if(i != map.end()) {                    count += i->second;                }            }        }        return count;    }};
原创粉丝点击