LeetCode 3Sum Smaller
2016-03-11 14:15
309 查看
原题链接在这里:https://leetcode.com/problems/3sum-smaller/
题目:
Given an array of n integers nums and a target, find the number of index triplets
For example, given nums =
Return 2. Because there are two triplets which sums are less than 2:
题解:
与3Sum类似. 计算和小于target的组合个数,重复的也要算. 若是nums[i] + nums[j] + nums[k] 符合要求,那么count += k-j, j++. 举例{-2, 0, 1, 3}. target = 4. {-2, 0, 3}符合要求, {-2, 0, 1}也符合要求,一次加上两个.
若是不符合要求说明等于或者大于target了, k--.
Time Complexity: O(n^2). Space: O(1).
AC Java:
题目:
Given an array of n integers nums and a target, find the number of index triplets
i, j, kwith
0 <= i < j < k < nthat 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]
题解:
与3Sum类似. 计算和小于target的组合个数,重复的也要算. 若是nums[i] + nums[j] + nums[k] 符合要求,那么count += k-j, j++. 举例{-2, 0, 1, 3}. target = 4. {-2, 0, 3}符合要求, {-2, 0, 1}也符合要求,一次加上两个.
若是不符合要求说明等于或者大于target了, k--.
Time Complexity: O(n^2). Space: O(1).
AC Java:
public class Solution { public int threeSumSmaller(int[] nums, int target) { if(nums == null || nums.length == 0){ return 0; } Arrays.sort(nums); int count = 0; for(int i = 0; i<nums.length-2; i++){ int j = i+1; int k = nums.length-1; while(j<k){ if(nums[i] + nums[j] + nums[k] >= target){ k--; }else{ count += k-j; j++; } } } return count; } }
相关文章推荐
- sql 操作表增加字段
- Chapter 11. Frame, MainWindow, and Toplevel Widgets 框架,主窗体,顶级部件
- Chapter 11. Frame, MainWindow, and Toplevel Widgets 框架,主窗体,顶级部件
- OC字符串和数组
- 使用_CrtSetDbgFlag检测内存泄露
- Google DeepMind围棋程序AlphaGo的分析
- leetcode 113. Path Sum II
- curl模拟post请求提交
- dwz 多选删除
- 微信第三方登录Android注意事项
- day1_android快捷键
- Java ReentrantLock和synchronize的对比
- ssl在tomcat 中的配置
- codeforces 651B Beautiful Paintings(贪心)
- 似然函数
- 学习python可以去看廖雪峰网站去看,写的很好
- android studio调试编译错误
- javascript统计输入文本的简易方法
- window.location.href的用法 (动态跳转)
- 网页向女友/老婆告白和纪念日专用特效