学习目标:
力扣第15题:三数之和
学习内容:
给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?请你找出所有满足条件且不重复的三元组。
注意:答案中不可以包含重复的三元组。
示例:
给定数组 nums = [-1, 0, 1, 2, -1, -4],
满足要求的三元组集合为:
[
[-1, 0, 1],
[-1, -1, 2]
]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/3sum
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
学习时间:
2020年10月26日
学习产出:
public List<List<Integer>> threeSum(int[] nums) {
ArrayList<List<Integer>> list = new ArrayList<List<Integer>>();
// 如果数组为空或者长度小于2,返回
if (nums == null || nums.length <= 2)
return list;
// 对数组进行排序
Arrays.sort(nums);
for (int i = 0; i < nums.length - 2; i++) {
//当第一个数大于0时,后面的数就全部大于0了
if (nums[i] > 0)
break;
//针对i去重
if (i > 0 && nums[i] == nums[i - 1]) {
continue;
}
int left = i + 1;
int right = nums.length - 1;
while (left < right) {
if (nums[i] + nums[left] + nums[right] == 0) {
//因为题目要求的是返回一个类型为List<Integer>的集合,
//因此将三个数转化为数组再添加进集合
list.add(Arrays.asList(nums[i], nums[left], nums[right]));
left++;
right--;
//针对指针去重,如果left指针与left-1相同,则继续往下走,right同理
while (left < right && nums[left] == nums[left - 1]) {
left++;
}
while (left < right && nums[right] == nums[right + 1]) {
right--;
}
} else if (nums[i] + nums[left] + nums[right] < 0) {
//如果三个数相加小于0,因为已经排序了,i不动,小一些的left指针往下走
left++;
} else {
right--;
}
}
}
return list;
}