PART2 双指针

移动零

lc.283

cpp 复制代码
class Solution {
public:
    void moveZeroes(vector<int>& nums) {
        int l = 0;
        for (int i = 0; i < nums.size(); i++) {
            if (nums[i] != 0) {
                swap(nums[i], nums[l]);
                l++;
            }
        }
    }
};

判断子序列

lc.392

cpp 复制代码
class Solution {
public:
    bool isSubsequence(string s, string t) {
        if (s.size() == 0) {
            return true;
        }
        if (s.size() > t.size()) {
            return false;
        }
        int currS = 0, currT = 0;
        while (currT < t.size() && currS < s.size()) {
            if (s[currS] == t[currT]) {
                currS++;
            }
            currT++;
        }
        return currS == s.size() && currT <= t.size();
    }
};

盛最多水的容器

lc.11

cpp 复制代码
class Solution {
public:
    int maxArea(vector<int>& height) {
        int left = 0, right = height.size() - 1;
        int maxV = 0;
        while (left < right) {
            int w = right - left;
            int h = min(height[left], height[right]);
            maxV = max(maxV, h * w);
            if (height[left] <= height[right]) {
                left++;
            } else {
                right--;
            }
        }
        return maxV;
    }
};

K和数对的最大数目

lc.1679

cpp 复制代码
class Solution {
public:
    int maxOperations(vector<int>& nums, int k) {
        int count = 0;
        int left = 0, right = nums.size() - 1;
        sort(nums.begin(), nums.end());
        while (left < right) {
            if (nums[left] + nums[right] == k) {
                count++;
                left++;
                right--;
            } else if (nums[left] + nums[right] < k) {
                left++;
            } else {
                right--;
            }
        }
        return count;
    }
};
相关推荐
tankeven2 小时前
HJ91 走方格的方案数
c++·算法
俩娃妈教编程2 小时前
2024 年 09 月 二级真题(2)--小杨的矩阵
c++·算法·gesp真题
航哥的女人2 小时前
Socket函数详解
c++·tcp/ip
浅念-2 小时前
C++ STL vector
java·开发语言·c++·经验分享·笔记·学习·算法
小雨中_2 小时前
2.8 策略梯度(Policy Gradient)算法 与 Actor-critic算法
人工智能·python·深度学习·算法·机器学习
程序员爱德华2 小时前
C++训练营学习大纲
c++
m0_531237172 小时前
C语言-if/else,switch/case
c语言·数据结构·算法
Hag_202 小时前
LeetCode Hot100 239.滑动窗口最大值
数据结构·算法·leetcode
漂流瓶jz2 小时前
UVA-1604 立体八数码问题 题解答案代码 算法竞赛入门经典第二版
算法·ida·深度优先·图论·dfs·bfs·迭代加深搜索