力扣hot100-5(盛最多水的容器),6(三数之和)

方法:双指针

java 复制代码
public class Solution {
    public int maxArea(int[] height) {
        int l = 0, r = height.length - 1;
        int ans = 0;
        while (l < r) {
            int area = Math.min(height[l], height[r]) * (r - l);
            ans = Math.max(ans, area);
            if (height[l] <= height[r]) {
                ++l;
            }
            else {
                --r;
            }
        }
        return ans;
    }
}

每次选取低的高度,同时哪边低就哪边往里缩。

java 复制代码
class Solution {
    public List<List<Integer>> threeSum(int[] nums) {
        int n = nums.length;
        Arrays.sort(nums);
        List<List<Integer>> ans = new ArrayList<List<Integer>>();//多态+泛型
        // 枚举 a
        for (int first = 0; first < n; ++first) {
            // 需要和上一次枚举的数不相同
            if (first > 0 && nums[first] == nums[first - 1]) {
                continue;
            }
            // c 对应的指针初始指向数组的最右端
            int third = n - 1;
            int target = -nums[first];
            // 枚举 b
            for (int second = first + 1; second < n; ++second) {
                // 需要和上一次枚举的数不相同
                if (second > first + 1 && nums[second] == nums[second - 1]) {
                    continue;
                }
                // 移动c指针,需要保证 b 的指针在 c 的指针的左侧
                while (second < third && nums[second] + nums[third] > target) {
                    --third;
                }
                // 如果指针重合,随着 b 后续的增加
                // 就不会有满足 a+b+c=0 并且 b<c 的 c 了,可以退出循环
                if (second == third) {
                    break;
                }
                if (nums[second] + nums[third] == target) {
                    List<Integer> list = new ArrayList<Integer>();
                    list.add(nums[first]);
                    list.add(nums[second]);
                    list.add(nums[third]);
                    ans.add(list);
                }//添加一种list集合
            }
        }
        return ans;
    }
}

a,b指针通过遍历来移动,c指针单独移动。

相关推荐
锅挤1 小时前
数据结构复习(第一章):绪论
数据结构·算法
汀、人工智能2 小时前
[特殊字符] 第95课:冗余连接
数据结构·算法·链表·数据库架构··冗余连接
生信研究猿2 小时前
leetcode 226.翻转二叉树
算法·leetcode·职场和发展
一只小白0002 小时前
反转单链表模板
数据结构·算法
橘颂TA2 小时前
【笔试】算法的暴力美学——牛客 WY22 :Fibonacci数列
算法
XWalnut2 小时前
LeetCode刷题 day9
java·算法·leetcode
bIo7lyA8v2 小时前
算法稳定性分析中的随机扰动建模的技术9
算法
谢白羽2 小时前
vllm抢占机制详解
算法·vllm
Hello--_--World2 小时前
Vue2的 双端 diff算法 与 Vue3 的 快速diff 算法
前端·vue.js·算法