leetcode15: 3Sum
来源:互联网 发布:数据是怎么传输的 编辑:程序博客网 时间:2024/06/05 14:53
ps:既然转向大数据,java是必须的技能。所以以后的leetcode都使用java来刷题。
题目
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]]
思路:
思路一:暴力破解,时间复杂度
思路二:针对每一个数字,找另外两个结果。
trick:考虑都是0的情况。
测试集
nums = []nums = [1, 4, 65, -1, 2, 6, -23, 0, -4, 8]nums = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0...., 0]nums = [1, 2]
代码
package leetcodeArray;import java.util.ArrayList;import java.util.LinkedList;import java.util.List;import java.util.Arrays;/** * leetcode 15题, 3sum * 主要考核数组的算法 * @author wq * */public class Sum3Solution { public List<List<Integer>> threeSum(int[] nums) { List<List<Integer>> result = new LinkedList<List<Integer>> (); if(nums.length < 3){ return result; } Arrays.sort(nums); for(int i = 0; i < nums.length - 2; i++){ if(i == 0 || ( i > 0 && nums[i] != nums[i-1])){ int low = i+1;int high = nums.length - 1; int iSum = 0 - nums[i]; while(low < high){ if(nums[low] + nums[high] == iSum){ result.add(Arrays.asList(nums[i], nums[low], nums[high])); while(low < high && nums[low] == nums[low+ 1]) low++; while(low < high && nums[high] == nums[high - 1]) high--; low++; high--; } else if( nums[low] + nums[high] > iSum){ high--; } else{ low++; } } } } return result; }}
阅读全文
0 0
- LeetCode15: 3 Sum
- LeetCode15:3Sum
- leetcode15 3Sum
- leetcode15 3Sum
- LeetCode15:3Sum
- leetcode15 3sum
- [LeetCode15]3Sum
- leetcode15---3Sum
- leetcode15.3Sum
- leetcode15:3Sum
- leetcode15:3Sum
- Leetcode15. 3Sum
- leetcode15. 3Sum
- leetcode15~3Sum
- leetcode15. 3Sum
- leetcode15. 3Sum
- LeetCode15. 3Sum
- leetcode15: 3Sum
- unit7-samba
- sqlldr使用简介
- kvm内存优化--KSM
- 【剑指offer-解题系列(53)】表示数值的字符串
- 使用echarts显示图表
- leetcode15: 3Sum
- 自定义广播
- 深度学习 3 循环神经网络 RNN Recurrent Neural Networks
- Redis的五种存储类型和其应用场景
- 从高考到程序员
- pygame 安装
- 信号捕捉&模拟sleep的简单实现
- 『四库全书安卓版』隐私政策
- spark-2017.06.08