leetcode15 3sum
2015-11-05 20:38
393 查看
我的leetcode代码已放入github:https://github.com/gaohongbin/leetcode
题目:
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.
翻译:
找到三个数相加之和为0,并且三个数是非递减顺序排列的。
思路:
对于2sum的问题,我们先对数组进行排列,然后用两个指针low和high分别指向数组的第一个数和最后一个数,因为是排过序的,所以当nums[low]+nums[high]之和小于target时,就low++,如果之和大于target,就high--,如果之和等于target,就将相应的nums[low],nums[high]保存起来。
对于3Sum问题,无非是外面加一层嵌套,相应的变换target为target-nums[one].
里面有个快排,纯属自己练手,可以引用线程的快排函数。
代码:
题目:
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.
翻译:
找到三个数相加之和为0,并且三个数是非递减顺序排列的。
思路:
对于2sum的问题,我们先对数组进行排列,然后用两个指针low和high分别指向数组的第一个数和最后一个数,因为是排过序的,所以当nums[low]+nums[high]之和小于target时,就low++,如果之和大于target,就high--,如果之和等于target,就将相应的nums[low],nums[high]保存起来。
对于3Sum问题,无非是外面加一层嵌套,相应的变换target为target-nums[one].
里面有个快排,纯属自己练手,可以引用线程的快排函数。
代码:
public List<List<Integer>> threeSum(int[] nums) { List<List<Integer>> list=new ArrayList<List<Integer>>(); if(nums==null || nums.length<3) return list; quickSort(nums,0,nums.length-1); int length=nums.length; int first=0; int two=first+1; int three=length-1; while(first<length-2){ two=first+1; three=length-1; while(two<three){ if(nums[two]+nums[three]>0-(nums[first]) && two<three){ three--; } if(nums[two]+nums[three]<0-nums[first] && two<three){ two++; } if(nums[two]+nums[three]==0-nums[first] && two<three){ List<Integer> listSum=new ArrayList<Integer>(); listSum.add(nums[first]); listSum.add(nums[two]); listSum.add(nums[three]); list.add(listSum); two++; while(two<three){ if(nums[two-1]==nums[two]) two++; if(nums[two-1]!=nums[two]) break; } } } first++; while( first<length-2 && nums[first-1]==nums[first] ) first++; } return list; } public void quickSort(int[] nums,int low,int high){ if(low>=high || nums==null) return ; int length=nums.length; int mid=nums[low]; int i=low,j=high; while(i<j){ while(nums[j]>mid && j>i) j--; nums[i]=nums[j]; while(nums[i]<=mid && i<j) i++; nums[j]=nums[i]; } nums[j]=mid; quickSort(nums,low,j-1); quickSort(nums,j+1,high); }
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解
- LeetCode [Day 5] Longest Palindromic Substring 题解