Leetcode刷题记——15. 3Sum(3个数字和)
来源:互联网 发布:js源代码加密 编辑:程序博客网 时间:2024/06/07 22:39
一、题目叙述:
Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
Note: The solution set must not contain duplicate triplets.
For example, given array S = [-1, 0, 1, 2, -1, -4],A solution set is:[ [-1, 0, 1], [-1, -1, 2]]
Subscribe to see which companies asked this question
二、解题思路:
激动咩激动咩,我爱编程!(虽然水平非常差)。恩,经典的求和问题,即从一组数里,输出三个数和为0的所有组合列表,我们之前做过2Sum咩。一看呢就不能用暴力的方法,必然超时。所以类似于2Sum的解法
(1)主体思路:循环前两个数,然后二分查找(所以数组要先排序)为前两数和的相反数的第三个数,这样复杂度能从O(n3)减到O(n2logn)。
(2)注意:列表里不能出现相同的组合!第一次我直接在找到第三个数时候循环判断了,与之前的组合相同的不添加进列表,傻不傻,前面改善算法得来的优势又被耗掉了,显而易见会超时。最后看了别人的代码,在第一个数和第二个数的循环开头分别加入一个判断,若之前已经用过这个数了,就跳过。
三、源码:
import java.util.ArrayList;import java.util.Arrays;import java.util.List;public class Solution {List<List<Integer>> ans = new ArrayList<List<Integer>>(); public List<List<Integer>> threeSum(int[] nums) { Arrays.sort(nums); int q; int h; //int count = 0; //List<List<Integer>> reslist = new ArrayList<List<Integer>>(); for (int i = 0; i < nums.length; i ++) { if (i > 0 && nums[i] == nums[i-1]) continue;//去除重复 for (int j = i + 1; j < nums.length; j++) { if (j > i+1 && nums[j] == nums[j-1]) continue;//去除重复 q = BinarySearch(-nums[i]-nums[j], nums, j+1, nums.length - 1); if (q > j) { //count ++; List<Integer> list = new ArrayList<Integer>(); list.add(nums[i]); list.add(nums[j]); list.add(nums[q]); ans.add(list); } } } return ans; } public int BinarySearch (int k,int[] num,int first, int last) { //int first = 0; //int last = num.length - 1; int mid; while (first <= last) { mid = (first + last) / 2; if (num[mid] > k) last =mid - 1; else if (num[mid] < k) first = mid + 1; else return mid; } return -1; } public static void main(String args[]) { int[] a = {0,0,0,0}; Solution so = new Solution(); System.out.println(so.threeSum(a)); }}
0 0
- Leetcode刷题记——15. 3Sum(3个数字和)
- Leetcode刷题记——18. 4Sum(4个数字和)
- Leetcode刷题记——16. 3Sum Closest(最接近的三个数的和)
- LeetCode刷题记录7-从数组中找出指定条件的3个数字
- leetcode题记——Two Sum
- LeetCode刷题记 3
- LeetCode刷题记录3-求数字是否为回文
- Leetcode刷题记——9. Palindrome Number(回文数字)
- 【LeetCode刷题记录】Two Sum
- leetcode刷题记录1:two sum
- leetcode刷题记录--Two Sum
- Leetcode刷题记——136. Single Number(单独的数字)
- LeetCode刷题记录3-Majority Element
- Leetcode刷题记——1.TwoSum
- Leetcode刷题记——41. First Missing Positive(第一个丢失的正数)
- leetcode— 3Sum
- leetcode 做题记录3
- Leetcode刷题记——17. Letter Combinations of a Phone Number(电话号码的数字组合)
- hadoop学习笔记之一:hadoop生态系统
- PhotoView 图片浏览缩放控件
- shiro安全框架扩展教程--如何扩展异步(ajax)请求认证失败处理
- token 在struts里的使用详解
- 第十周--项目2-二叉树遍历的递归算法
- Leetcode刷题记——15. 3Sum(3个数字和)
- 关于属性中包含shadow的属性
- 关于margin-top溢出父节点元素的处理方法
- npm install 无响应解决方案
- 关于串口接收的处理策略
- Bootstrap 学习之(十五)------ 媒体对象,well
- React Native CSS样式传递
- Unity摄像机旋转以及拉近拉远代码
- spring boot 中使用定时器