[LeetCode] 3Sum Smaller

Problem Description:

Given an array of n integers nums and a target, find the number of index triplets i, j, k with 0 <= i < j < k < n that satisfy the condition nums[i] + nums[j] + nums[k] < target.

For example, given nums = [-2, 0, 1, 3], and target = 2.

Return 2. Because there are two triplets which sums are less than 2:

[-2, 0, 1]
[-2, 0, 3]

Follow up:
Could you solve it in O(n^2) runtime?


Sort nums first and then fix the left index (i) at each time while adjusting the middle and right indexes (j, k). The following code should be self-explanatory.

复制代码
 1 class Solution {
 2 public:
 3     int threeSumSmaller(vector<int>& nums, int target) {
 4         sort(nums.begin(), nums.end());
 5         int n = nums.size(), ans = 0, i, j, k;
 6         for (int i = 0; i < n - 2; i++) {
 7             int j = i + 1, k = n - 1;
 8             while (j < k) {
 9                 if (nums[i] + nums[j] + nums[k] >= target) k--;
10                 else {
11                     ans += (k - j);
12                     j++;
13                 }
14             }
15         }
16         return ans;
17     }
18 };
复制代码

 

posted @   jianchao-li  阅读(5077)  评论(0编辑  收藏  举报
编辑推荐:
· dotnet 源代码生成器分析器入门
· ASP.NET Core 模型验证消息的本地化新姿势
· 对象命名为何需要避免'-er'和'-or'后缀
· SQL Server如何跟踪自动统计信息更新?
· AI与.NET技术实操系列:使用Catalyst进行自然语言处理
阅读排行:
· dotnet 源代码生成器分析器入门
· 官方的 MCP C# SDK:csharp-sdk
· 一款 .NET 开源、功能强大的远程连接管理工具,支持 RDP、VNC、SSH 等多种主流协议!
· 一步一步教你部署ktransformers,大内存单显卡用上Deepseek-R1
· 一次Java后端服务间歇性响应慢的问题排查记录
点击右上角即可分享
微信分享提示