博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode 923. 3Sum With Multiplicity
阅读量:4622 次
发布时间:2019-06-09

本文共 1695 字,大约阅读时间需要 5 分钟。

原题链接在这里:

题目:

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 = 8Output: 20Explanation: 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 = 5Output: 12Explanation: 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  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
target){18 r--;19 }else if(A[l] != A[r]){20 int leftCount = 1;21 int rightCount = 1;22 while(l+1

 

转载于:https://www.cnblogs.com/Dylan-Java-NYC/p/11376454.html

你可能感兴趣的文章
把 MongoDB 当成是纯内存数据库来使用(Redis 风格)
查看>>
PyTorch 1.0 中文官方教程:使用ONNX将模型从PyTorch传输到Caffe2和移动端
查看>>
LeetCode 4Sum
查看>>
BBC-The Race and a quiz
查看>>
大端小端
查看>>
IntelliJ IDEA 把java项目导出成可执行的jar
查看>>
DynamicReports
查看>>
鼠标经过图像改变实现
查看>>
二分查找法
查看>>
Spring3升级到Spring4时, 运行时出现找不到MappingJacksonHttpMessageConverter的情况
查看>>
详解缓冲区溢出攻击以及防范方法
查看>>
分布式事务解决方案(一) 2阶段提交 & 3阶段提交 & TCC
查看>>
android之网格布局和线性布局实现注册页面
查看>>
BZOJ 1014: [JSOI2008]火星人prefix( splay + hash )
查看>>
安装ejabberd2并配置MySQL为其数据库
查看>>
angular repeat
查看>>
android 图片圆角化控件
查看>>
java第三次作业
查看>>
HP Jack介绍
查看>>
敏捷软件开发(3)---COMMAND 模式 & Active Object 模式
查看>>