代码随想录leetcode200题之双指针法

目录

  • 1 介绍
  • 2 训练
  • 3 参考

1 介绍

本博客用来记录代码随想录leetcode200题中双指针算法部分的题目。

2 训练

题目1:27. 移除元素

C++代码如下,

class Solution {
public:
    int removeElement(vector<int>& nums, int val) {
        int j = 0;
        for (int i = 0; i < nums.size(); ++i) {
            if (nums[i] == val) {
                //
            } else {
                nums[j++] = nums[i];
            }
        }
        return j;
    }
};

python3代码如下,

class Solution:
    def removeElement(self, nums: List[int], val: int) -> int:
        j = 0
        for i in range(len(nums)):
            if nums[i] == val:
                pass
            else:
                nums[j] = nums[i]
                j += 1
        return j

题目2:344. 反转字符串

C++代码如下,

class Solution {
public:
    void reverseString(vector<char>& s) {
        int l = 0, r = s.size() - 1;
        while (l <= r) swap(s[l++], s[r--]);
        return;
    }
};

python3代码如下,

class Solution:
    def reverseString(self, s: List[str]) -> None:
        """
        Do not return anything, modify s in-place instead.
        """
        l = 0
        r = len(s) - 1
        while l <= r:
            s[l], s[r] = s[r], s[l]
            l += 1
            r -= 1
        return 

题目3:54. 替换数字(第八期模拟笔试)

C++代码如下,

#include <iostream>
#include <string>

using namespace std;

int main() {
    string s;
    cin >> s;
    
    string res;
    for (auto c : s) {
        if (c >= 'a' && c <= 'z') res += c;
        else res += "number";
    }
    cout << res << endl;
    
    return 0;
}

python3代码如下,

s = str(input())
res = ""
for c in s:
    if c.isdigit():
        res += "number"
    else:
        res += c 
print(res)

题目4:151. 反转字符串中的单词

C++代码如下,

class Solution {
public:
    string reverseWords(string s) {
        vector<string> words;
        int n = s.size();
        for (int i = 0; i < n; ++i) {
            if (s[i] != ' ') {
                string t = "";
                while (i < n && s[i] != ' ') {
                    t += s[i];
                    i += 1;
                }
                words.emplace_back(t);
            }
        }

        reverse(words.begin(), words.end());
        string res = "";
        for (auto word : words) {
            res += word + " ";
        }
        res = res.substr(0, res.size()-1);
        return res;
    }
};

python3代码如下,

class Solution:
    def reverseWords(self, s: str) -> str:
        ls = s.split()
        ls = ls[::-1]
        res = ""
        for x in ls:
            res += x + " "
        res = res[0:-1]
        return res

题目5:206. 反转链表

C++代码如下,

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        if (head == nullptr || head->next == nullptr) { //特判空集或一个结点的时候
            return head;
        }

        ListNode* a = head;
        ListNode* b = a->next;

        while (a != nullptr && b != nullptr) {
            ListNode* t = b->next;
            b->next = a;

            a = b;
            b = t;
        }
        
        head->next = nullptr;
        return a;
    }
};

python3代码如下,

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
        if head is None or head.next is None: #特判空集和一个结点的情况
            return head 

        a = head 
        b = a.next 
        while a is not None and b is not None:
            t = b.next

            b.next = a 

            a = b
            b = t 
        
        head.next = None 
        return a

题目6:19. 删除链表的倒数第 N 个结点

C++代码如下,

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* removeNthFromEnd(ListNode* head, int k) {
        //删除倒数第k个结点,快慢指针法

        ListNode* dummy = new ListNode(0, head);

        ListNode* a = dummy;
        ListNode* b = dummy;

        while (k--) { //b先走k步
            b = b->next;
        }

        while (b->next != nullptr) { //b走到最后一个结点
            a = a->next;
            b = b->next;
        }

        if (a->next != nullptr) a->next = a->next->next;
        else cout << "a->next is nullptr!" << endl;

        return dummy->next;
    }
};

python3代码如下,

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def removeNthFromEnd(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
        dummy = ListNode(0, head)
        a = dummy
        b = dummy 

        while k > 0:
            b = b.next
            k -= 1

        while b.next is not None:
            b = b.next 
            a = a.next 
        
        a.next = a.next.next 
        return dummy.next 

题目7:面试题 02.07. 链表相交

C++代码如下,

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
        if(headA == nullptr || headB == nullptr) { //特判都为空集,或者有一方为空集的情况
            return nullptr;
        }
        
        ListNode* a = headA;
        ListNode* b = headB;

        bool flaga = true;
        bool flagb = true;
        while (a != b) {
            a = a->next;
            b = b->next;

            if (a == nullptr) {
                if (flaga) {
                    a = headB;
                    flaga = false;
                } else {
                    break;
                }
            }

            if (b == nullptr) {
                if (flagb) {
                    b = headA;
                    flagb = false;
                } else {
                    break;
                }
            }
        }

        if (a == b) return a;
        else return nullptr;
    }
};

python3代码如下,

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:
        if headA is None or headB is None:
            return None 
        
        a = headA 
        b = headB 
        flaga = True
        flagb = True 
        while a != b:
            a = a.next 
            b = b.next 

            if a is None:
                if flaga:
                    a = headB 
                    flaga = False
                else:
                    break 
            
            if b is None:
                if flagb:
                    b = headA 
                    flagb = False 
                else:
                    break 
        
        if a == b:
            return a 
        else:
            return None

题目8:142. 环形链表 II

C++代码如下,

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *detectCycle(ListNode *head) {
        //这次的快慢指针,是速度上的快慢指针,而非提前走的快慢指针
        ListNode* a = head;
        ListNode* b = head;

        while (b != nullptr && b->next != nullptr) {
            a = a->next;
            b = b->next->next;

            //起点到环入口的距离为x
            //快慢指针相遇点到环入口的距离为y
            //环的周长为c
            //有x % c = y恒成立
            if (a == b) { 
                ListNode* t = head;
                while (t != a) {
                    t = t->next;
                    a = a->next;
                }
                return a;
            }
        }
        return nullptr;
    }
};

python3代码如下,

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def detectCycle(self, head: Optional[ListNode]) -> Optional[ListNode]:
        a = head 
        b = head 

        while b is not None and b.next is not None:
            a = a.next 
            b = b.next.next 

            if a == b:
                t = head 
                while t != a:
                    t = t.next 
                    a = a.next 
                return a 
        return None 
        

题目9:15. 三数之和

C++代码如下,

class Solution {
public:
    vector<vector<int>> threeSum(vector<int>& nums) {
        map<int, int> map_val_cnt;
        for (auto x : nums) map_val_cnt[x]++;

        vector<int> vals;
        for (auto [k, v] : map_val_cnt) vals.emplace_back(k);

        set<int> vis;
        for (auto x : vals) vis.insert(x);

        int n = vals.size();
        set<vector<int>> ans;
        for (int i = 0; i < n; ++i) {
            int a = vals[i];
            for (int j = 0; j < n; ++j) {
                int b = vals[j];
                int c = 0 - a - b;
                if (vis.count(c) != 0) {
                    unordered_map<int,int> curr_cnt;
                    curr_cnt[a]++;
                    curr_cnt[b]++;
                    curr_cnt[c]++;
                    if (curr_cnt[a] <= map_val_cnt[a] && 
                    curr_cnt[b] <= map_val_cnt[b] &&
                    curr_cnt[c] <= map_val_cnt[c]) {
                        vector<int> t = {a, b, c};
                        sort(t.begin(), t.end());
                        ans.insert(t);
                    }
                }
            }
        }

        vector<vector<int>> res(ans.begin(), ans.end());
        return res;
    }
};

python3代码如下,

class Solution:
    def threeSum(self, nums: List[int]) -> List[List[int]]:
        map_val_cnt = collections.defaultdict(int)
        for x in nums:
            map_val_cnt[x] += 1
        
        vals = []
        for val in map_val_cnt:
            vals.append(val)

        vis = set()
        for val in vals:
            vis.add(val)
        
        ans = set()
        n = len(vals)
        for i in range(n):
            a = vals[i]
            for j in range(n):
                b = vals[j]
                c = 0 - a - b
                if c in vis:
                    curr_cnt = collections.defaultdict(int)
                    curr_cnt[a] += 1
                    curr_cnt[b] += 1
                    curr_cnt[c] += 1

                    if curr_cnt[a] <= map_val_cnt[a] and \
                    curr_cnt[b] <= map_val_cnt[b] and \
                    curr_cnt[c] <= map_val_cnt[c]:
                        t = [a, b, c]
                        t.sort()
                        ans.add(tuple(t))
        ans = list(ans)
        ans = [list(x) for x in ans]
        return ans

题目10:18. 四数之和

C++代码如下,

typedef long long LL;

class Solution {
public:
    vector<vector<int>> fourSum(vector<int>& nums, int target) {
        map<int, int> map_val_cnt;
        for (auto x : nums) map_val_cnt[x] += 1;

        vector<int> vals;
        set<int> vis;
        for (auto [k, v] : map_val_cnt) {
            vals.emplace_back(k);
            vis.insert(k);
        }

        set<vector<int>> ans;
        int n = vals.size();
        for (int i = 0; i < n; ++i) {
            for (int j = 0; j < n; ++j) {
                for (int k = 0; k < n; ++k) {
                    int a = vals[i];
                    int b = vals[j];
                    int c = vals[k];
                    LL t = (LL)target - a - b - c;
                    
                    if (t > INT_MAX || t < INT_MIN) { //如果t超出了整型范围,那么vis.count(d)一定为0
                        continue;
                    }

                    int d = (LL)target - a - b - c;

                    if (vis.count(d) != 0) { 
                        unordered_map<int,int> curr_cnt;
                        curr_cnt[a]++;
                        curr_cnt[b]++;
                        curr_cnt[c]++;
                        curr_cnt[d]++;
                        if (curr_cnt[a] <= map_val_cnt[a] && curr_cnt[b] <= map_val_cnt[b] &&
                        curr_cnt[c] <= map_val_cnt[c] && curr_cnt[d] <= map_val_cnt[d]) {
                            vector<int> t = {a, b, c, d};
                            sort(t.begin(), t.end());
                            ans.insert(t);
                        }
                    }
                }
            }
        }

        vector<vector<int>> res(ans.begin(), ans.end());
        return res;
    }
};

python3代码如下,

class Solution:
    def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
        map_val_cnt = collections.defaultdict(int)
        for x in nums:
            map_val_cnt[x] += 1
        
        vals = []
        vis = set()
        for x in map_val_cnt:
            vals.append(x)
            vis.add(x)
        
        ans = set()
        n = len(vals)
        for i in range(n):
            for j in range(n):
                for k in range(n):
                    a = vals[i]
                    b = vals[j]
                    c = vals[k]
                    d = target - a - b - c 
                    if d in vis:
                        curr_cnt = collections.defaultdict(int)
                        curr_cnt[a] += 1
                        curr_cnt[b] += 1
                        curr_cnt[c] += 1
                        curr_cnt[d] += 1
                        if curr_cnt[a] <= map_val_cnt[a] and curr_cnt[b] <= map_val_cnt[b] and \
                        curr_cnt[c] <= map_val_cnt[c] and curr_cnt[d] <= map_val_cnt[d]:
                            t = [a, b, c, d]
                            t.sort()
                            t = tuple(t)
                            ans.add(t)
        res = list(ans)
        res = [list(x) for x in res]
        return res

3 参考

代码随想录官网

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/600945.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

LLMs之GPT4ALL:GPT4ALL的简介、安装和使用方法、案例应用之详细攻略

LLMs之GPT4ALL&#xff1a;GPT4ALL的简介、安装和使用方法、案例应用之详细攻略 目录 GPT4ALL的简介 0、新功能 1、特点 2、功能 3、技术报告 GPT4ALL的安装和使用方法 1、安装 2、使用方法 GPT4ALL的案例应用 LLMs之LLaMA3&#xff1a;基于GPT4ALL框架对LLaMA-3实现…

【笔记】Anaconda命令提示符(Anaconda Prompt)操作

通过anaconda配置python环境有时需要conda安装一些包或者文件&#xff0c;这里作为一个笔记记录如何打开Anaconda命令提示符&#xff08;Anaconda Prompt&#xff09;&#xff0c;并用conda操作 1.打开Anaconda命令提示符&#xff08;Anaconda Prompt&#xff09; 可直接在搜…

如何获得一个Oracle 23ai数据库(RPM安装)

准确的说&#xff0c;是Oracle 23ai Free Developer版&#xff0c;因为企业版目前只在云上&#xff08;OCI和Azure&#xff09;和ECC上提供。 方法包括3种&#xff0c;本文介绍第2种&#xff1a; Virtual ApplianceRPM安装Docker RPM安装支持Linux 8和Linux 9。由于官方的Vi…

人工智能|机器学习——强大的 Scikit-learn 可视化让模型说话

一、显示 API 简介 使用 utils.discovery.all_displays 查找可用的 API。 Sklearn 的utils.discovery.all_displays可以让你看到哪些类可以使用。 from sklearn.utils.discovery import all_displays displays all_displays() displays Scikit-learn (sklearn) 总是会在新版本…

Stack数据结构设计模板

第三章 栈、队列、数组 1.栈 1.1 顺序栈 #define MaxSize 20 typedef int ElemType; //顺序栈的定义 typedef struct {ElemType data[MaxSize];int top; }SqStack; // 初始化顺序栈 void InitSqStack(SqStack &S){S.top -1; }; // 入栈(增) bool Push(SqStack &S,El…

推荐5个免费的国内平替版GPT

提起AI&#xff0c;大家第一个想到的就是GPT。 虽然它确实很厉害&#xff0c;但奈何于我们水土不服&#xff0c;使用门槛有些高。 不过随着GPT的爆火&#xff0c;现在AI智能工具已经遍布到各行各业了&#xff0c;随着时间的推移&#xff0c;国内的AI工具也已经“百花盛放”了…

【R语言从0到精通】-4-回归建模

通过之前的文章&#xff0c;我们已经基本掌握了R语言的基本使用方法&#xff0c;那从本次教程开始&#xff0c;我们开始聚焦如何使用R语言进行回归建模。 4.1 回归简介 回归分析是一种统计学方法&#xff0c;用于研究两个或多个变量之间的相互关系和依赖程度。它可以帮助我们了…

Java性能优化(一):Java基础-ArrayList和LinkedList

引言 集合作为一种存储数据的容器&#xff0c;是我们日常开发中使用最频繁的对象类型之一。JDK为开发者提供了一系列的集合类型&#xff0c;这些集合类型使用不同的数据结构来实现。因此&#xff0c;不同的集合类型&#xff0c;使用场景也不同。 很多同学在面试的时候&#x…

数控六面钻适用场景-不止家具制造

在快节奏的现代生活中&#xff0c;家具作为我们生活的重要组成部分&#xff0c;其美观度和实用性日益受到人们的关注。而在这背后&#xff0c;一个不可或缺的“工匠”正默默地发挥着它的作用——那就是数控六面钻。 数控六面钻&#xff0c;顾名思义&#xff0c;是一种高度自动…

OS复习笔记ch5-2

引言 在上一篇笔记中&#xff0c;我们介绍到了进程同步和进程互斥&#xff0c;以及用硬件层面上的三种方法分别实现进程互斥。其实&#xff0c;软件层面上也有四种方法&#xff0c;但是这些方法大部分都存在着一些问题&#xff1a; “上锁”与“检查”是非原子操作&#xff0…

error: pathspec ‘XXX‘ did not match any file(s) known to git

使用vscode&#xff0c;在本地开发切换分支时&#xff0c;报以下错误&#xff1a; error: pathspec XXX did not match any file(s) known to git 该问题是由于没有对应分支的原因。 首先使用一下命令&#xff0c;查看本地及远程的所有分支。 git branch -a 若没有对应的分…

47.Redis学习笔记

小林coding -> 图解redis的学习笔记 文章目录 Rediswindwos安装docker安装redis启动redis使用RDM访问虚拟机中的redispython连接redis缓存穿透、击穿、雪崩基本数据类型高级数据类型高并发指标布隆过滤器分布式锁Redis 的有序集合底层为什么要用跳表&#xff0c;而不用平衡…

谷歌推出10门免费AI课程,无需教科书及费用

谷歌面向小白以及开发者分别推出了不同的AI课程~ 包含初级、中级和高级。课程章节大致包括&#xff1a;&#xff08;含教学视频、参考材料、测验&#xff09; 基础入门&#xff1a;45分钟深入了解生成式AI 简单实操&#xff1a;30分钟掌握大语言模型 了解如何释放生成式 AI S…

基于小程序实现的投票评选系统

作者主页&#xff1a;Java码库 主营内容&#xff1a;SpringBoot、Vue、SSM、HLMT、Jsp、PHP、Nodejs、Python、爬虫、数据可视化、小程序、安卓app等设计与开发。 收藏点赞不迷路 关注作者有好处 文末获取源码 技术选型 【后端】&#xff1a;Java 【框架】&#xff1a;spring…

CSS选择器(基本+复合+伪类)

目录 CSS选择器 基本选择器 标签选择器&#xff1a;使用标签名作为选择器->选中同名标签设置样式 类选择器&#xff1a;给类选择器定义一个名字.类名&#xff0c;并给标签添加class"类名" id选择器&#xff1a;跟类选择器非常相似&#xff0c;给id选择器定义…

数据库数据恢复—SQL Server数据库ndf文件变为0KB的数据恢复案例

SQL Server数据库故障&#xff1a; 存储设备损坏导致存储中SQL Server数据库崩溃。对数据库文件进行恢复后&#xff0c;用户发现有4个ndf文件的大小变为0KB。该SQL Server数据库每10天生成一个大小相同的NDF文件&#xff0c;该SQL Server数据库包含两个LDF文件。 SQL Server数据…

Node.js里面 Path 模块的介绍和使用

Node.js path 模块提供了一些用于处理文件路径的小工具&#xff0c;我们可以通过以下方式引入该模块&#xff1a; var path require("path") 方法描述 序号方法 & 描述1path.normalize(p) 规范化路径&#xff0c;注意.. 和 .。2path.join([path1][, path2][,…

将矩阵按对角线排序(Lc1329)——排序

矩阵对角线 是一条从矩阵最上面行或者最左侧列中的某个元素开始的对角线&#xff0c;沿右下方向一直到矩阵末尾的元素。例如&#xff0c;矩阵 mat 有 6 行 3 列&#xff0c;从 mat[2][0] 开始的 矩阵对角线 将会经过 mat[2][0]、mat[3][1] 和 mat[4][2] 。 给你一个 m * n 的整…

Vue创建todolist

电子书 第三章&#xff1a; https://www.dedao.cn/ebook/reader?idV5R16yPmaYOMqGRAv82jkX4KDe175w7xRQ0rbx6pNgznl9VZPLJQyEBodb89mqoO 没有使用VUE CLI创建项目。 创建步骤&#xff1a; 1&#xff0c; 用Vite 创建项目 2&#xff0c; npm run dev 运行程序 参照之前的文…

[Kubernetes] Rancher 2.7.5 部署 k8s

server: 192.168.66.100 master: 192.168.66.101 node1: 192.168.66.102 文章目录 1.rancher server 安装docker2.部署k8s3.kubeconfig 1.rancher server 安装docker 所有主机开通ipv4 vi /etc/sysctl.conf#加入 net.ipv4.ip_forward 1#配置生效 sysctl -prancher-server开通…
最新文章