threeSum
来源:互联网 发布:淘宝卖蜂蜜要什么条件 编辑:程序博客网 时间:2024/04/29 15:15
public List<List<Integer>> threeSum(int[] nums) { Arrays.sort(nums); List<List<Integer>> resultlist=new ArrayList<List<Integer>>(); if(nums.length<3) { return resultlist; } for(int i=0;i<nums.length-2;i++) { if (i > 0 && nums[i] == nums[i - 1]) { continue; } int j=i+1; int k=nums.length-1; int target=-nums[i]; while(j<k) { if(target==nums[j]+nums[k]) { List<Integer> arraylist=new ArrayList(); arraylist.add((Integer)nums[i]); arraylist.add((Integer)nums[j]); arraylist.add((Integer)nums[k]); resultlist.add(arraylist); j++; k--; while (j < k && nums[j] == nums[j - 1]) j++; while (j < k && nums[k] == nums[k + 1]) k--; } else if(nums[j]+nums[k]>target) { k--; } else if(nums[j]+nums[k]<target) { j++; } } } return resultlist; }
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]]
第一次编程时出现了超时的问题:
class Solution { public List<List<Integer>> threeSum(int[] nums) { Arrays.sort(nums); List<List<Integer>> resultlist=new ArrayList<List<Integer>>(); if(nums.length<3) { return resultlist; } 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 sum=nums[i]+nums[j]; int third=0-sum; for(int k=j+1;k<nums.length;k++) { if(nums[k]==third) { List<Integer> arraylist=new ArrayList(); arraylist.add((Integer)nums[i]); arraylist.add((Integer)nums[j]); arraylist.add((Integer)nums[k]); resultlist.add(arraylist); break; } } } } return resultlist; }}最后通过学习,用了新的算法:
阅读全文
0 0
- threeSum
- threeSum
- threeSum
- LeetCode ThreeSum
- leetcode : threesum
- ThreeSum的问题
- [各种面试题] threesum
- threeSum and fourSum
- LeetCode之ThreeSum
- 【蓝桥第四周】ThreeSum
- LeetCode(M)threesum
- [LeetCode]15.threeSum
- leetcode 15 threeSum
- LeetCode(三)关于ThreeSum的实现
- Leetcode 之 twoSum, ThreeSum, FourSum(K-Sum)问题
- 算法练习专题——LeetCode系列之 ThreeSum
- Hibernate框架简介(个人总结及理解)
- 01.奇特的一生——柳比歇夫一生的秘密
- 大数据预科21(补充之反射)
- cron表达式详解
- vueJs(2.x)+router+vuex简易博客系统<二>
- threeSum
- libvirt q35 报错
- ORACLE 日期加减操作
- Unreal Editor中调用exe
- 多线程爬虫案例(浅)一
- WEB API接口
- Docker第二篇:架构的基本组成
- Handler 设置首界面页面跳转
- vin码详解以及自动扫描vin码识别应用