leetcode hot100 双指针

力扣hot100双指针模块整理回顾。如有缺漏谬误,还请批评指正。

1.移动零

思想:把非零元素前移,剩下的全部补0。

引入idx记录非零索引,在遍历整理数组的同时,更新非零元素索引,然后把剩下的空位(idx~n之间)全部填补成0。

class Solution {
public:
    void moveZeroes(vector& nums) {
        int n=nums.size();
        int idx=0;
        for(int i=0;i

2.盛最多水的容器

核心:木桶效应。

两个柱子之间能盛多少水取决于高度更短的那一方(min(height[i],height[j]))。

引入左指针i和右指针j进行遍历更新。

class Solution {
public:
    int maxArea(vector& height) {
       int n=height.size();
       int i=0,j=n-1;
       int maxv=0;
       while(i<=j){
            maxv=max(maxv,min(height[i],height[j])*(j-i));
            if(height[i]

3.三数之和

思想:先对数组排序,然后固定一个数nums[i],并在[i+1,n-1]区间遍历另外两个数nums[l]和nums[r]。

细节处理:当找到一组答案后,l后移,r前移,由于答案不可以包含重复的三元组,所以需要跳过重复元素。

class Solution {
public:
    vector> threeSum(vector& nums) {
        vector> res;
        int n=nums.size();
        if(n<3) return res;
        sort(nums.begin(),nums.end());
        for(int i=0;i0&&nums[i]==nums[i-1]) continue;  
            int l=i+1,r=n-1;
            while(l

4.接雨水

核心:还是木桶效应,每次依据“短板”更新储水量,第二题进阶版。

class Solution {
public:
    int trap(vector& height) {
        int n=height.size();
        int i=0,j=n-1;
        int res=0,lmax=0,rmax=0;
        //每块“地”能储多少水取决于“短板”,所以首先需要if判断
        //“短板”需要及时更新
        //储水量=“短板”高度-当前“地块”高度
        while(i<=j){
            if(height[i]

 

 

 

你可能感兴趣的:(leetcode,算法,数据结构)