leetcode 454. 4Sum II
来源:互联网 发布:jsp网上订餐系统源码 编辑:程序博客网 时间:2024/06/05 09:45
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这一题我原来想了想,好像没啥好办法。然后用n^4的循环来做,不出所料地TLE了。
后来看了大神的解法,我才知道原来可以分解。将4个数组的和,转化为,两个数组的和+两个数组的和。即找出AB数组和的所有可能性,再找出CD数组和的所有可能性,再判断两个和是否加起来=0,这样把O(n^4)转化为O(n^2) 。
package leetcode;import java.util.HashMap;public class Sum_II_4_454 {public int fourSumCount(int[] A, int[] B, int[] C, int[] D) {int count=0;int n=A.length;HashMap<Integer, Integer> mapAB=new HashMap<Integer, Integer>();for(int pointerA=0;pointerA<n;pointerA++){for(int pointerB=0;pointerB<n;pointerB++){int sum=A[pointerA]+B[pointerB];mapAB.put(sum, mapAB.getOrDefault(sum, 0)+1);}}for(int pointerC=0;pointerC<n;pointerC++){for(int pointerD=0;pointerD<n;pointerD++){int sum=C[pointerC]+D[pointerD];if(mapAB.get(-sum)!=null){count+=mapAB.get(-sum);}}}return count;}public static void main(String[] args) {// TODO Auto-generated method stubSum_II_4_454 s=new Sum_II_4_454();int[] A=new int[]{1,2};int[] B=new int[]{-2,-1};int[] C=new int[]{-1,2};int[] D=new int[]{0,2};System.out.println(s.fourSumCount(A, B, C, D));}}
Time complexity: O(n^2)
Space complexity: O(n^2)
阅读全文
0 0
- LeetCode 454. 4Sum II
- Leetcode-454. 4Sum II
- LeetCode 454. 4Sum II
- Leetcode-454. 4Sum II
- 【LeetCode】 454. 4Sum II
- [leetcode]454. 4Sum II
- 【Leetcode】454. 4Sum II
- Leetcode 454. 4Sum II
- LeetCode 454. 4Sum II
- [LeetCode] 454. 4Sum II
- leetcode 454. 4Sum II
- leetcode 454. 4Sum II
- LeetCode 454. 4Sum II
- Leetcode: 454. 4Sum II
- leetcode 454. 4Sum II
- leetcode 454. 4Sum II
- [leetcode] 454. 4Sum II
- [LeetCode] 4Sum II
- Jmeter参数化
- 微信Android模块化架构重构实践
- Selenium+java分层(六)
- Hibernate基于注解方式的各种映射全面总结
- 《大话设计模式》——读后感 (2)商场促销?——策略模式
- leetcode 454. 4Sum II
- Python 字符串,字典,数据库,列表和json互相转化
- BT How-to
- Snackbar碰到的坑
- 1008 选数
- Java 引用方式
- 《大话设计模式》——读后感 (3)穿什么有这么重要?——装饰模式之理论实例(1)
- activiti:initiator详解
- An ffmpeg and SDL Tutorial 学习笔记(五)