LeetCode 454. 4Sum II ***** 灵活的设定键

来源:互联网 发布:淘宝活动怎样能找到 编辑:程序博客网 时间:2024/06/15 09:29

    • 题目
      • 题意
      • 注意
      • 思路
      • 代码
      • 结果
      • 区别于184Sum

题目

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:
2

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

题意

给定4个整型数组A,B,C,D,计算它们中的元素(i,j,k,l)有多少中组合,使得A[i]+B[j]+C[k]+D[i] = 0

注意

由于A,B,C,D是整型数组,它们的长度是否一致。(题目给出长度一致),并且数据量0 ≤ N ≤ 500.
无解返回什么
根据数据量,再设计算法的时候要考虑选择什么样的算法。
O(n^4) = 62 500 000 000 O(n^3) = 125 000 000
O(n^2) = 250 000
这里写图片描述
从这个数据量可以看出,至少应该选择的O(n^2)的算法

思路

1.a+b+c+d = 0 —–> a + b = 0 - c - d = - ( c + d )
2.求出c与d和的组合,放在表中
3.再求出a+b的和是否在表中,若在就添加频率

代码

class Solution {public:    int fourSumCount(vector<int>& A, vector<int>& B, vector<int>& C, vector<int>& D) {        //A+B+C+D = 0----->C+D=0-A-B        //map<int,int> record; //对于数据量大的,unordered_map的效率显著  725ms        unordered_map<int,int> record;  //hash-map        for(auto c:C)  //统计C+D的频率        {            for(auto d:D)            {                record[c+d]++;            }        }                int res = 0;        for(auto a:A) //遍历A+B的和是否在表中,若在就更新满足条件的组合数        {            for(auto b:B)            {                if(record.find(0-a-b)!=record.end())                {                    //若:c+d的和出现2次,可能的组合就+2                    res+=record[0-a-b];                }            }        }                return res;    }};

结果

这里写图片描述

区别于18.4Sum

  • 4Sum II是求出有多少种组合,a,b,c,d可包含重复元素。返回多少种组合
  • 4Sum 不能包含重复重复解。返回符合条件的元素
  • 所有尽管4Sum II的方法更为简单清晰,却不能应用到4Sum上
原创粉丝点击