259:较小的三数之和

This commit is contained in:
轩辕龙儿 2022-03-28 16:51:44 +08:00
parent 73741d281d
commit 3839ed4c93
2 changed files with 117 additions and 0 deletions

View File

@ -0,0 +1,80 @@
//给定一个长度为 n 的整数数组和一个目标值 target 寻找能够使条件 nums[i] + nums[j] + nums[k] < target 成立的
//三元组 i, j, k 个数0 <= i < j < k < n
//
//
//
// 示例 1
//
//
//输入: nums = [-2,0,1,3], target = 2
//输出: 2
//解释: 因为一共有两个三元组满足累加和小于 2:
//  [-2,0,1]
// [-2,0,3]
//
//
// 示例 2
//
//
//输入: nums = [], target = 0
//输出: 0
//
// 示例 3
//
//
//输入: nums = [0], target = 0
//输出: 0
//
//
//
// 提示:
//
//
// n == nums.length
// 0 <= n <= 3500
// -100 <= nums[i] <= 100
// -100 <= target <= 100
//
// Related Topics 数组 双指针 二分查找 排序 👍 106 👎 0
package leetcode.editor.cn;
import java.util.Arrays;
//259:较小的三数之和
public class ThreeSumSmaller {
public static void main(String[] args) {
Solution solution = new ThreeSumSmaller().new Solution();
// TO TEST
solution.threeSumSmaller(new int[]{-1, 1, -1, -1}, -1);
}
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public int threeSumSmaller(int[] nums, int target) {
if (nums == null || nums.length == 0) {
return 0;
}
Arrays.sort(nums);
int sum;
int count = 0;
for (int i = 0; i < nums.length; i++) {
int left = i + 1;
int right = nums.length - 1;
while (left < right) {
sum = nums[i] + nums[left] + nums[right];
if (sum < target) {
count += (right - left);
left++;
} else {
right--;
}
}
}
return count;
}
}
//leetcode submit region end(Prohibit modification and deletion)
}

View File

@ -0,0 +1,37 @@
<p>给定一个长度为 <code>n</code> 的整数数组和一个目标值 <code>target</code>&nbsp;,寻找能够使条件&nbsp;<code>nums[i] + nums[j] + nums[k] &lt; target</code>&nbsp;成立的三元组&nbsp; <code>i, j, k</code>&nbsp;个数(<code>0 &lt;= i &lt; j &lt; k &lt; n</code>)。</p>
<p>&nbsp;</p>
<p><strong>示例 1</strong></p>
<pre>
<strong>输入: </strong><em>nums</em> = <code>[-2,0,1,3]</code>, <em>target</em> = 2
<strong>输出: </strong>2
<strong>解释: </strong>因为一共有两个三元组满足累加和小于 2:
&nbsp; [-2,0,1]
[-2,0,3]
</pre>
<p><strong>示例 2</strong></p>
<pre>
<strong>输入: </strong><em>nums</em> = <code>[]</code>, <em>target</em> = 0
<strong>输出: </strong>0 </pre>
<p><strong>示例 3</strong></p>
<pre>
<strong>输入: </strong><em>nums</em> = <code>[0]</code>, <em>target</em> = 0
<strong>输出: </strong>0 </pre>
<p>&nbsp;</p>
<p><strong>提示:</strong></p>
<ul>
<li><code>n == nums.length</code></li>
<li><code>0 &lt;= n &lt;= 3500</code></li>
<li><code>-100 &lt;= nums[i] &lt;= 100</code></li>
<li><code>-100 &lt;= target &lt;= 100</code></li>
</ul>
<div><div>Related Topics</div><div><li>数组</li><li>双指针</li><li>二分查找</li><li>排序</li></div></div><br><div><li>👍 106</li><li>👎 0</li></div>