15. 3Sum
Posted lyinfo
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了15. 3Sum相关的知识,希望对你有一定的参考价值。
Given an array nums of n integers, are there elements a, b, c in nums 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.
Example:
Given array nums = [-1, 0, 1, 2, -1, -4],
A solution set is:
[
[-1, 0, 1],
[-1, -1, 2]
]
看了半天没啥想法,时间复杂度不要了,暴力解之~
1 public static List<List<Integer>> threeSum(int[] nums) { 2 int len = nums.length; 3 List<List<Integer>> result = new ArrayList<>(); 4 //3个for循环找和为零的组合(要求是n个和就n个嵌套for循环,汗!!!) 5 for (int i = 0; i < len; i++) { 6 for (int j = i + 1; j < len; j++) { 7 for (int k = len - 1; k > j; k--) { 8 if (nums[i] + nums[j] + nums[k] == 0) { 9 List<Integer> member = Arrays.asList(nums[i], nums[j], nums[k]); 10 result.add(member); 11 } 12 } 13 } 14 } 15 16 //获得要去重的元素的索引 17 List<Integer> removeList = new ArrayList<>(); 18 for (int i = 0; i < result.size(); i++) { 19 List<Integer> tempi = result.get(i); 20 for (int j = i + 1; j < result.size(); j++) { 21 List<Integer> tempj = result.get(j); 22 Collections.sort(tempi); 23 Collections.sort(tempj); 24 for (int k = 0; k < 3; k++) { 25 if (tempi.get(k) != tempj.get(k)) { 26 break; 27 } 28 if (k == 2) { 29 removeList.add(i); 30 } 31 } 32 } 33 } 34 35 //直接remove会引起索引值变化 36 for (int i = 0; i < result.size(); i++) { 37 for (Integer integer : removeList) { 38 if (i == integer) { 39 result.set(i, null); 40 } 41 } 42 } 43 for (Iterator<List<Integer>> iterator = result.iterator(); iterator.hasNext();) { 44 List<Integer> list = (List<Integer>) iterator.next(); 45 if (list == null) { 46 iterator.remove(); 47 } 48 } 49 return result; 50 }
测试效果
public static void main(String[] args) { int[] nums = { -1, 0, 1, 2, -1, -4 }; List<List<Integer>> result = threeSum(nums); for (List<Integer> list : result) { System.out.println(list.toString()); } }
结果貌似也是对的,但是以我对leetcode的了解,必然timeOut,提交试试
内心毫无波澜,百度之,看了一圈发现,可以从1. Two Sum问题入手,通过排序优化数值查找过程,继续。
以上是关于15. 3Sum的主要内容,如果未能解决你的问题,请参考以下文章