본문으로 바로가기

Description

배열의 요소 3개의 합이 target이 되는 경우의 수를 반환하는 문제입니다.

Given an integer array arr, and an integer target, return the number of tuples i, j, k such that i < j < k and arr[i] + arr[j] + arr[k] == target.

As the answer can be very large, return it modulo 109 + 7.

Example 1:

Input: arr = [1,1,2,2,3,3,4,4,5,5], target = 8
Output: 20
Explanation:
Enumerating by the values (arr[i], arr[j], arr[k]):
(1, 2, 5) occurs 8 times;
(1, 3, 4) occurs 8 times;
(2, 2, 4) occurs 2 times;
(2, 3, 3) occurs 2 times.

Example 2:

Input: arr = [1,1,2,2,2,2], target = 5
Output: 12
Explanation:
arr[i] = 1, arr[j] = arr[k] = 2 occurs 12 times:
We choose one 1 from [1,1] in 2 ways,
and two 2s from [2,2,2,2] in 6 ways.

Constraints:

  • 3 <= arr.length <= 3000
  • 0 <= arr[i] <= 100
  • 0 <= target <= 300

Solution 1. Hash Table

public int threeSumMulti(int[] arr, int target) {

    HashMap<Integer, Integer> map = new HashMap<>();
    int length = arr.length;
    long result = 0;

    for(int i = 0; i + 1 < length; i++){
        for(int j = i + 1; j < length; j++){
            if(map.containsKey(target - arr[i] - arr[j])){
                result += 1L * map.get(target - arr[i] - arr[j]);
            }
        }
        map.put(arr[i], map.getOrDefault(arr[i], 0) + 1);
    }
    return (int) (result%(1000000007));

}

배열을 반복하며 target 에 현재 i,j의 요소를 뺀 요소가 있다면 해당 요소의 개수를 결과에 추가해 주고 현재 요소를 기록해 줍니다.

Reference

 

3Sum With Multiplicity - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com