内容简介:上面的情况是有问题的,会超时比如都是0的情况,就很有很多无用的判断,还有就是没有解决重复性的问题,解决重复性之前的思路是通过set解决,但为了结局超时的情况,决定排序,也能解决重复性的问题。再确定一个数后,在后面的有序数组中,也可以通过双指针确定是否存在符合条件的值public List<List<Integer>> threeSum(int[] nums) {
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] ]
所有情况应该是o(n^3)的情况,可以通过HashMap优化到o(n^2)
public List<List<Integer>> threeSum(int[] nums) {
HashMap<Integer,Integer> map=new HashMap();
HashSet<List<Integer>> set=new HashSet();
for(int i:nums){
if(map.containsKey(i)) map.put(i,map.get(i)+1);
else map.put(i+1);
}
for(int i=0;i<nums.length-1;i++){
for(int j=i+1;j<nums.length){
int need=-nums[i]-nums[j];
if(need==nums[i] == need==nums[i]){
if(map.get(need)<3) continue;
}else if(need==nums[i] || need==nums[i]){
if(map.get(need)<2) continue;
}else{
if(map.get(need)<1) continue;
}
List<Integer> list=Arrays.asList(new int[]{nums[i],nums[j],need});
}
}
return new ArrayList(set);
}
上面的情况是有问题的,会超时比如都是0的情况,就很有很多无用的判断,还有就是没有解决重复性的问题,解决重复性之前的思路是通过set解决,但为了结局超时的情况,决定排序,也能解决重复性的问题。
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> ret=new ArrayList();
Arrays.sort(nums);
Map<Integer,Integer> map=new HashMap();
for(int i=0;i<nums.length;i++) map.put(nums[i],i);
for(int i=0;i<nums.length-2;i++){
if(i>0 && nums[i]==nums[i-1]) continue;
for(int j=i+1;j<nums.length-1;j++){
if(j>i+1 && nums[j]==nums[j-1]) continue;
int need=-nums[i]-nums[j];
if(need>=nums[j] && map.getOrDefault(need,-1)>j) ret.add(Arrays.asList(nums[i],nums[j],need));
}
}
return ret;
}
再确定一个数后,在后面的有序数组中,也可以通过双指针确定是否存在符合条件的值
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> ret=new ArrayList();
Arrays.sort(nums);
for(int i=0;i<nums.length-2;i++){
if(i>0 && nums[i]==nums[i-1]) continue;
int left=i+1;
int right=nums.length-1;
while(right>left){
if(left>i+1 && nums[left]==nums[left-1]) {
left++;
continue;
}
if(right<nums.length-1 && nums[right]==nums[right+1]){
right--;
continue;
}
if(nums[i]+nums[left]+nums[right]<0) left++;
else{
if(nums[i]+nums[left]+nums[right]==0) ret.add(Arrays.asList(nums[i],nums[left],nums[right]));
right--;
}
}
}
return ret;
}
以上所述就是小编给大家介绍的《[LeetCode]15. 3Sum》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!
猜你喜欢:本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Writing Apache Modules with Perl and C
Lincoln Stein、Doug MacEachern / O'Reilly Media, Inc. / 1999-03 / USD 39.95
Apache is the most popular Web server on the Internet because it is free, reliable, and extensible. The availability of the source code and the modular design of Apache makes it possible to extend Web......一起来看看 《Writing Apache Modules with Perl and C》 这本书的介绍吧!