Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 | 29 |
30 | 31 |
Tags
- 코테
- hash table
- Class
- simulation
- Method
- database
- dynamic programming
- SQL
- bit manipulation
- Counting
- greedy
- Tree
- implement
- java
- sorting
- Stack
- string
- Data Structure
- Math
- 코딩테스트
- 자바
- geometry
- Binary Tree
- array
- Number Theory
- Matrix
- 파이썬
- 구현
- Binary Search
- two pointers
Archives
- Today
- Total
코린이의 소소한 공부노트
[LeetCode/Medium] 454. 4Sum II 본문
1. Input
1) int[] nums1
2) int[] nums2
3) int[] nums3
4) int[] nums4
2. Output
1) 각 배열에서 1개씩 뽑아 만든 네 수의 합이 0이 되는 순서쌍의 개수를 반환
3. Constraint
1) n == nums1.length == nums2.length == nums3.length == nums4.length
2) 1 <= n <= 200
3) - 2^28 <= nums1[i], nums2[i], nums3[i], nums4[i] <= 2^28
4. Example
Input: nums1 = [1,2], nums2 = [-2,-1], nums3 = [-1,2], nums4 = [0,2] -> Output: 2
설명:
- nums1[0] + nums2[0] + nums3[0] + nums4[1] = 1 + (-2) + (-1) + 2 = 0
- nums1[1] + nums2[1] + nums3[0] + nums4[0] = 2 + (-1) + (-1) + 0 = 0
5. Code
1) 첫 코드(2023/02/22)
int answer = 0;
HashMap<Integer,Integer> m1 = new HashMap<Integer,Integer>();
for(int a : nums1){
for(int b : nums2){
if(m1.containsKey(a+b)) m1.put(a+b, m1.get(a+b)+1);
else m1.put(a+b, 1);
}
}
HashMap<Integer,Integer> m2 = new HashMap<Integer,Integer>();
for(int a : nums3){
for(int b : nums4){
if(m2.containsKey(a+b)) m2.put(a+b, m2.get(a+b)+1);
else m2.put(a+b, 1);
}
}
Iterator it = m1.keySet().iterator();
while(it.hasNext()){
int a = (int)it.next();
if(m2.containsKey(-a))
answer += (int)m1.get(a) * (int)m2.get(-a);
}
return answer;
- 반복횟수를 줄여보고자 2개로 나눠서 짜봤는데, 역시나 성능이 별로다.
'코딩테스트 풀이 > JAVA' 카테고리의 다른 글
[프로그래머스/Lv.2] 행렬의 곱셈 (0) | 2023.02.22 |
---|---|
[LeetCode/Easy] 455. Assign Cookies (0) | 2023.02.22 |
[LeetCode/Medium] 442. Find All Duplicates in an Array (0) | 2023.02.21 |
[LeetCode/Medium] 438. Find All Anagrams in a String (0) | 2023.02.21 |
[프로그래머스/Lv.1] 카드 뭉치 (0) | 2023.02.20 |