链表算法题(程序员面试宝典)
解题思路主要来源于leetcode官方与《程序员面试宝典》。
15. 三数之和
给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?请你找出所有和为 0 且不重复的三元组。
注意:答案中不可以包含重复的三元组。
示例 1:
输入:nums = [-1,0,1,2,-1,-4]
输出:[[-1,-1,2],[-1,0,1]]
示例 2:
输入:nums = []
输出:[]
示例 3:
输入:nums = [0]
输出:[]
提示:
0 <= nums.length <= 3000
-105 <= nums[i] <= 105
解题方法
解题思路1
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
//返回值
List<List<Integer>> res = new ArrayList<List<Integer>>();
if(nums.length<3){
return new ArrayList<List<Integer>>();
}
for(int i=0;i<nums.length-2;i++){
for(int j=i+1;j<nums.length-1;j++){
for(int k=j+1;k<nums.length;k++){
if(nums[i]+nums[j]+nums[k]==0){
List<Integer> val = new ArrayList<Integer>();
val.add(nums[i]);
val.add(nums[j]);
val.add(nums[k]);
//排序
Collections.sort(val);
if(!res.contains(val)){
res.add(val);
}
}
}
}
}
return res;
}
}
解题思路2
解题思路来源:https://leetcode-cn.com/problems/3sum/solution/pai-xu-shuang-zhi-zhen-zhu-xing-jie-shi-python3-by/
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
//返回值
List<List<Integer>> res = new ArrayList<List<Integer>>();
//当数组长度小于3时,返回
if(nums.length<3){
return new ArrayList<List<Integer>>();
}
//对数组先进行排序
Arrays.sort(nums);
//循环遍历数组
for(int i=0;i<nums.length;i++){
//数组以按从小到大排列,if nums[i]>0 则后三位数一定相加一定不为0
if(nums[i]>0){
return res;
}
//对于重复元素,直接跳过,避免重复解
if(i>0&&nums[i]==nums[i-1]){
continue;
}
int L = i+1;
int R = nums.length-1;
while(L<R){
if(nums[i]+nums[L]+nums[R]==0){
List<Integer> val = new ArrayList<>();
val.add(nums[i]);
val.add(nums[L]);
val.add(nums[R]);
res.add(val);
while(L<R&&nums[L]==nums[L+1]){
//对于重复元素,直接跳过,避免重复解
L=L+1;
}
while(L<R&&nums[R]==nums[R-1]){
//对于重复元素,直接跳过,避免重复解
R=R-1;
}
L = L+1;
R = R-1;
}else if(nums[i]+nums[L]+nums[R]>0){
//取更小值
R = R-1;
}else if(nums[i]+nums[L]+nums[R]<0){
//整体取更大值
L = L+1;
}
}
}
return res;
}
}