LeetCode Hot100_15. 三数之和

题目链接:15. 三数之和 - 力扣(LeetCode)

三个指针法: i指针从头开始遍历指导倒数第三个,在循环内设置指针j、k,初始值分别为i+1和n-1,这样就都能遍历到。

 1 class Solution {
 2     public List<List<Integer>> threeSum(int[] nums) {
 3         List<List<Integer>> res = new ArrayList<>();
 4         Arrays.sort(nums); // nlogn
 5         for (int i = 0; i < nums.length - 2; i++) {
 6             // 跳过重复的 nums[i]
 7             if (i > 0 && nums[i] == nums[i - 1]) {
 8                 continue;
 9             }
10 
11             int left = i + 1; // 左指针
12             int right = nums.length - 1; // 右指针
13 
14             while (left < right) {
15                 int sum = nums[i] + nums[left] + nums[right];
16 
17                 if (sum == 0) {
18                     // 找到一组解
19                     res.add(Arrays.asList(nums[i], nums[left], nums[right]));
20 
21                     // 跳过重复的 nums[left] 和 nums[right]
22                     while (left < right && nums[left] == nums[left + 1]) left++;
23                     while (left < right && nums[right] == nums[right - 1]) right--;
24 
25                     // 移动指针
26                     left++;
27                     right--;
28                 } else if (sum < 0) {
29                     // 和太小,左指针右移
30                     left++;
31                 } else {
32                     // 和太大,右指针左移
33                     right--;
34                 }
35             }
36         }
37 
38         return res;
39     }
40 }

 

posted @ 2025-02-09 11:37  烟雨化飞龙  阅读(7)  评论(0)    收藏  举报