码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode 4Sum II

时间:2017-12-03 13:00:50      阅读:134      评论:0      收藏:0      [点我收藏+]

标签:复杂   ati   tuples   block   int   题目   4行   for   lists   

454. 4Sum II

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) +

跟之前写的TwoSum一样使用哈希表即可简化计算时间复杂度的水题
题目固定的给出A B C D四行需要4行中的列的组合为0,时间复杂度为o(\(n4\))但是和为0等价于有两个相反数存在,所以将其分为AB一组, CD一组即可.时间复杂度为O(\(n^2\))

class Solution {
public:
    int fourSumCount(vector<int>& A, vector<int>& B, vector<int>& C, vector<int>& D) {
        map<int, int>m;
        for(int i = 0; i<A.size(); i++){
            for(int j=0; j<B.size(); j++){
                m[A[i]+B[j]]++;
            }
        }
        int resultNum  = 0;
        for(int i = 0; i<C.size(); i++){
            for(int j =0; j<D.size(); j++){
                int reverse = C[i]+D[j];
                resultNum += m[-1*reverse];
            }
        }
        return resultNum;
    }
};

leetcode 4Sum II

标签:复杂   ati   tuples   block   int   题目   4行   for   lists   

原文地址:http://www.cnblogs.com/Dyleaf/p/7965725.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!