欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Leetcode 454. 4Sum II

程序员文章站 2024-01-17 23:42:28
...

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

method 1 转化为3Sum

做过前面的题的思想就会想到将4Sum转化为3Sum,但这个方法会TLE

int fourSumCount3(vector<int>& A, vector<int>& B, vector<int>& C, vector<int>& D) {
	int count = 0;
	unordered_map<int, vector<int>> map;
	for (int i = 0; i < D.size(); i++){
		vector<int> v;
		if (!map.count(D[i])){
			v.push_back(i);
			map[D[i]] = v;
		}
		else{
			v = map[D[i]];
			v.push_back(i);
			map[D[i]] = v;
		}

	}
	for (int i = 0; i < A.size(); i++){
		for (int j = 0; j < B.size(); j++){
			for (int k = 0; k < C.size(); k++){
				int sum3 = A[i] + B[j] + C[k];
				if (map.count(-sum3)){
					vector<int> index = map[-sum3];
					count += index.size();
				}
			}
		}
	}

	return count;
}

method 2 合并数组转化为2Sum

因为本题只需要返回count,而不需要返回具体每个数组相应的索引,因此我们可以将4个数组合并为两个数组,同时记录相同值的个数,然后4Sum就会转化为2Sum。

int fourSumCount(vector<int>& A, vector<int>& B, vector<int>& C, vector<int>& D) {
	unordered_map<int, int> map1;
	unordered_map<int, int> map2;

	for (int i = 0; i < A.size(); i++)
	{
		for (int j = 0; j < B.size(); j++)
		{
			//for map1
			int sumAB = A[i] + B[j];
			if (!map1.count(sumAB)){
				map1[sumAB] = 1;
			}
			else map1[sumAB]++;

			//for map2
			int sumCD = C[i] + D[j];
			if (!map2.count(sumCD)){
				map2[sumCD] = 1;
			}
			else map2[sumCD]++;
		}
	}

	int count = 0;
	unordered_map<int, int>::iterator iter = map1.begin();
	for (; iter != map1.end(); iter++)
	{
		int sumAB = iter->first;
		if (map2.count(-sumAB)) count += (iter->second * map2[-sumAB]);
	}

	return count;
}

method 3 binary Search

本题如果要使用二分查找,也是同样的思路,在ABsum的vector遍历,然后再CDsum的vector中二分查找,只是要考虑下如何再二分查找中统计相同的所有个数
和2Sum中的binary Search差不多

summary

  1. 用binary Search在一个有序序列中查找某一个数