LeetCode 923. 3Sum With Multiplicity

原题链接在这里:https://leetcode.com/problems/3sum-with-multiplicity/

题目:

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

As the answer can be very large, return it modulo 10^9 + 7.

 

Example 1:

Input: A = [1,1,2,2,3,3,4,4,5,5], target = 8
Output: 20
Explanation: 
Enumerating by the values (A[i], A[j], A[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: A = [1,1,2,2,2,2], target = 5
Output: 12
Explanation: 
A[i] = 1, A[j] = A[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.

Note:

  1. 3 <= A.length <= 3000
  2. 0 <= A[i] <= 100
  3. 0 <= target <= 300

题解:

Perform 3Sum and find the target.

Here there are 2 cases:

1. A[l] != A[r], count the frequency of A[l] and A[r], possible number of tuples is leftCount*rightCount.

e.g. 2333, A[l] = 2, A[r] = 3, leftCount = 1, rightCount = 3, number of types is 1*3 = 3.

2. A[l] == A[r], number of tupes is count*(count-1)/2.

e.g. 222, A[l] = 2, A[r] = 2, number of tupes 3*2/2 = 3. There are 3 ways to pick 2 elements from it.

Time Compelxity: O(n^2). n = A.length.

Space: O(1).

AC Java:

 1 class Solution {
 2     public int threeSumMulti(int[] A, int target) {
 3         if(A == null || A.length == 0){
 4             return 0;
 5         }
 6         
 7         int res = 0;
 8         int M = 1000000000+7;
 9         Arrays.sort(A);
10         for(int i = 0; i<A.length-2; i++){
11             int l = i+1;
12             int r = A.length-1;
13             while(l<r){
14                 int sum = A[i] + A[l] + A[r];
15                 if(sum < target){
16                     l++;
17                 }else if(sum > target){
18                     r--;
19                 }else if(A[l] != A[r]){
20                     int leftCount = 1;
21                     int rightCount = 1;
22                     while(l+1<r && A[l]==A[l+1]){
23                         leftCount++;
24                         l++;
25                     }
26                     
27                     while(l+1<r && A[r]==A[r-1]){
28                         rightCount++;
29                         r--;
30                     }
31                     
32                     res += leftCount*rightCount;
33                     res = res%M;
34                     l++;
35                     r--;
36                 }else{
37                     // A[l] == A[r]
38                     res += (r-l+1)*(r-l)/2;
39                     res = res%M;
40                     break;
41                 }
42             }
43         }
44         
45         return res;
46     }
47 }

 

上一篇:微信小程序参考资料及网址


下一篇:HTML标签大全