LeetCode Algorithm 0016 - 0020

LeetCode Algorithm 0062 - Unique Paths (Medium) 0062 - Unique Paths (Medium) 阅读详情

LeetCode Algorithm 0016 - 0020



0016 - 3Sum Closest (Medium)

Problem Link: https://leetcode.com/problems/3sum-closest/description/

Description

Given an array nums of n integers and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution.

Example:

Given array nums = [-1, 2, 1, -4], and target = 1.

The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).

Solution C++

#pragma once

#include "pch.h"

// Problem: https://leetcode.com/problems/3sum-closest/description/

namespace P16ThreeSumClosest
{
    class Solution
    {
        public:
        int threeSumClosest(vector<int>& nums, int target)
        {
            // 没有3个数
            if (nums.empty() || nums.size() < 3)
            {
                return -1;
            }

            // 排序
            sort(nums.begin(), nums.end());
        
            int result = nums[0] + nums[1] + nums[nums.size() - 1];

            for (size_t i = 0; i < nums.size() - 2; i++)
            {
                int leftIndex = i + 1;
                int rightIndex = nums.size() - 1;

                while (leftIndex < rightIndex)
                {
                    int sum = nums[i] + nums[leftIndex] + nums[rightIndex];
                    if (sum > target)
                    {
                        rightIndex--;
                    }
                    else
                    {
                        leftIndex++;
                    }

                    if (abs(sum - target) < abs(result - target))
                    {
                        result = sum;
                    }
                }
            }

            return result;
        }
    };
}


0017 - Letter Combinations of a Phone Number (Medium)

Problem Link: https://leetcode.com/problems/letter-combinations-of-a-phone-number/description/

Description

Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent.

A mapping of digit to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.

question 17

Example:

Input: "23"
Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].

Note:

Although the above answer is in lexicographical order, your answer could be in any order you want.

Solution C++

#pragma once

#include "pch.h"

// Problem: https://leetcode.com/problems/letter-combinations-of-a-phone-number/description/

namespace P17LetterCombinationsOfAPhoneNumber
{
    class Solution
    {
        public:
        vector<string> letterCombinations(string digits)
        {
            if (digits.empty())
            {
                return vector<string>();
            }

            unordered_map<char, string> map;
            map['0'] = " ";
            map['1'] = "*";
            map['2'] = "abc";
            map['3'] = "def";
            map['4'] = "ghi";
            map['5'] = "jkl";
            map['6'] = "mno";
            map['7'] = "pqrs";
            map['8'] = "tuv";
            map['9'] = "wxyz";

            vector<string> result = NextLetters(map, digits, { "" });
            return result;
        }

        private:
        vector<string> NextLetters(unordered_map<char, string> map, string digits, vector<string> lastLetters)
        {
            if (digits.empty())
            {
                return lastLetters;
            }

            if (digits[0] < '0' || digits[0] > '9')
            {
                runtime_error e = runtime_error(
                    "ValueError: invalid literal for int() with base 10: " + digits[0]);
                throw e;
            }

            vector<string> letters = vector<string>();
            for (size_t i = 0; i < lastLetters.size(); i++)
            {
                for (size_t j = 0; j < map[digits[0]].size(); j++)
                {
                    string letter = lastLetters[i];
                    letter.push_back(map[digits[0]][j]);
                    letters.push_back(letter);
                }
            }

            return NextLetters(map, digits.substr(1), letters);
        }
    };
}


0018 - 4Sum (Medium)

Problem Link: https://leetcode.com/problems/4sum/description/

Description

Given an array nums of n integers and an integer target, are there elements a, b, c, and d in nums such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.

Note:

The solution set must not contain duplicate quadruplets.

Example:

Given array nums = [1, 0, -1, 0, -2, 2], and target = 0.

A solution set is:
[
  [-1,  0, 0, 1],
  [-2, -1, 1, 2],
  [-2,  0, 0, 2]
]

Solution C++

#pragma once

#include "pch.h"

// Problem: https://leetcode.com/problems/4sum/description/

namespace P18FourSum
{
    class Solution
    {
        public:
        vector<vector<int>> fourSum(vector<int>& nums, int target)
        {
            if (nums.size() < 4)
            {
                return {};
            }

            // 排序
            sort(nums.begin(), nums.end());

            vector<vector<int>> results = {};
            FindSum(nums, 0, target, 4, {}, results);
            return results;
        }

        private:
        void FindSum(vector<int>& nums,
                     int startIndex, 
                     int target, 
                     int numCount, 
                     vector<int> result, 
                     vector<vector<int>>& results)
        {
            if (numCount < 2)
            {
                return;
            }

            int size = nums.size();
            if (numCount != 2)
            {
                for (int i = startIndex; i < size - numCount + 1; i++)
                {
                    if (target < nums[i] * numCount || target > nums[size - 1] * numCount)
                    {
                        break;
                    }

                    if (i == startIndex || (i > startIndex && nums[i - 1] != nums[i]))
                    {
                        vector<int> cur = vector<int>(result);
                        cur.push_back(nums[i]);
                        FindSum(nums, i + 1, target - nums[i], numCount - 1, cur, results);
                    }
                }
            }
            else
            {
                int leftIndex = startIndex, rightIndex = size - 1;
                while (leftIndex < rightIndex)
                {
                    if (nums[leftIndex] + nums[rightIndex] == target)
                    {
                        vector<int> cur = vector<int>(result);
                        cur.push_back(nums[leftIndex]);
                        cur.push_back(nums[rightIndex]);
                        results.push_back(cur);
                        leftIndex++;
                        rightIndex--;
                        while (leftIndex < rightIndex && nums[leftIndex] == nums[leftIndex - 1])
                        {
                            leftIndex++;
                        }
                        while (leftIndex < rightIndex && nums[rightIndex] == nums[rightIndex + 1])
                        {
                            rightIndex--;
                        }
                    }
                    else if (nums[leftIndex] + nums[rightIndex] < target)
                    {
                        leftIndex++;
                    }
                    else
                    {
                        rightIndex--;
                    }
                }
            }
        }
    };
}


0019 - Remove Nth Node From End of List (Medium)

Problem Link: https://leetcode.com/problems/remove-nth-node-from-end-of-list/description/

Description

Given a linked list, remove the n -th node from the end of list and return its head.

Example:

Given linked list: 1->2->3->4->5, and n = 2.

After removing the second node from the end, the linked list becomes 1->2->3->5.

Note:

Given n will always be valid.

Follow up:

Could you do this in one pass?

Solution C++

#pragma once

#include "pch.h"

// Problem: https://leetcode.com/problems/remove-nth-node-from-end-of-list/description/

namespace P19RemoveNthNodeFromEndOfList
{
    struct ListNode
    {
        int val;
        ListNode *next;
        ListNode(int x) : val(x), next(NULL)
        {
        }
    };

    class Solution
    {
        public:
        ListNode* removeNthFromEnd(ListNode* head, int n)
        {
            ListNode* start = new ListNode(0);
            start->next = head;

            ListNode* right = start;
            for (int i = 0; i < n; i++)
            {
                right = right->next;
            }

            ListNode* left = start;
            while (right->next != NULL)
            {
                left = left->next;
                right = right->next;
            }

            left->next = left->next->next;

            return start->next;
        }
    };
}


0020 - Valid Parentheses (Easy)

Problem Link: https://leetcode.com/problems/valid-parentheses/description/

Description

Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.

An input string is valid if:

  • 1. Open brackets must be closed by the same type of brackets.
  • 2. Open brackets must be closed in the correct order.

Note that an empty string is also considered valid.

Example 1:

Input: "()"
Output: true

Example 2:

Input: "()[]{}"
Output: true

Example 3:

Input: "(]"
Output: false

Example 4:

Input: "([)]"
Output: false

Example 5:

Input: "{[]}"
Output: true

Solution C++

#pragma once

#include "pch.h"

// Problem: https://leetcode.com/problems/valid-parentheses/description/

namespace P20ValidParentheses
{
    class Solution
    {
        private:
        unordered_map<char, char> brackets = { {'(', ')'}, {'[', ']'}, {'{', '}'} };

        public:
        bool isValid(string s)
        {
            if (s.empty())
            {
                return true;
            }

            stack<char> chStack;
            for (size_t i = 0; i < s.size(); i++)
            {
                if (brackets.find(s[i]) != brackets.end())
                {
                    chStack.push(s[i]);
                    continue;
                }

                if (chStack.size() == 0)
                {
                    return false;
                }

                if (brackets[chStack.top()] == s[i])
                {
                    chStack.pop();
                }
                else
                {
                    return false;
                }
            }

            return chStack.size() == 0;
        }
    };
}


BEVFormer vs BEVFusion:5个关键差异点帮你选对环视感知方案 本文深入对比了自动驾驶领域两大主流环视感知方案BEVFormer与BEVFusion。BEVFormer作为纯视觉BEV感知的标杆,通过注意力机制隐式学习深度,成本较低;而BEVFusion作为多模态融合典范,融合激光雷达与摄像头数据,在性能、小目标检测及极端环境鲁棒性上优势显著。文章从计算效率、部署成本、数据依赖性等五个核心维度提供选型指南,帮助技术决策者根据自身算力预算与传感器配置做出明智选择。 阅读详情

相关推荐

python实现语音信号的分帧、加窗、预处理

语音信号实现分帧、加窗、预处理音频文件读取预加重分帧加窗 音频文件读取 librosa是非常强大的python语音信号处理库。 读取音频: 使用语句librosa.load(path, sr=22050, mono=True, offset=0.0, duration=None)读取音频文件,默认的采样率是22050,若要保留音频的原始采样率,使用sr=None。 其中: path:表示音频文件的路径 sr:表示采样率 mono:bool,是布尔类型,表示是否将信号转换为单声道 offset:float,后

weixin_45272908的博客 1万+

LeetCode Algorithm Menu (算法目录)

这个目录是记录我刷 LeetCode 算法题的过程,其中代码使用的是C++,不定期更新。

DarkRabbit的专栏 612

MFC下使用C++操作Word文档

由于项目需求,在MFC环境下操作将数据和图片写入word文档,之前没有接触过,网上查阅了很多资料,终于把任务完成。理解的不是很透彻,但是这些东西应该够用了,写篇博客记录一下,以便以后再用到。 (1)VS环境下创建一个MFC应用程序,然后在项目上单击右键,选择 类向导-----添加类----类型库中的MFC类。在弹出的对话框中选择文件,位置选择office安装目录下的...

GIS_yuhua的博客 7594

LeetCode Algorithm 0041 - 0045

0041 - First Missing Positive (Hard) 0042 - Trapping Rain Water (Hard) 0043 - Multiply Strings (Medium) 0044 - Wildcard Matching (Hard) 0045 - Jump Game II (Hard)

DarkRabbit的专栏 441

WINDOWS下SIP拨号的实现

在WIN10上拨打SIP电话  由于我的交换原理实验有一个是关于SIP的抓包的。而之前从未接触过SIP,所以在如何完成一次SIP拨号上遇到了不少问题,查了好多资料都没有完整的或者写的很清楚的,这里就对那些资料做一个总结,给出一个比较完善的解决方案,一来是记录此次实验的收获,而来也可能为其他有同样困惑的人解惑。  废话不多说直接开始。首先是下载一个可以拨打SIP电话的客户终端,这里我选择的是MicroSIP, 下载红圈内的文件,下载好之后直接一路安装即可,没有什么特别注意的地方。  安装好客户端之后,就需要注

weixin_43918519的博客 3823

【Azure 架构师学习笔记】- Azure Private Endpoint

公有云的其中一个特点是默认允许公网访问, 这就对企业环境带来风险,也是很多年前企业对公有云抵触的其中一个原因,现在这类问题已经很少,因为有了很多技术来确保云上的资源被安全地访问。其中Private endpoint(PE)就起到了很重要的作用。云上的某个资源如VM会创建在特定的网络(VNet/Subnet)上, 而其他如Storage Account , Azure SQL等PaaS服务则没有。如果你需要用VM 来访问这些PaaS资源,VM 就会通过资源的公网IP 来访问。

MVP黄钊吉(發糞塗牆) 1793

LeetCode Algorithm 0036 - 0040

0036 - Valid Sudoku (Medium) 0037 - Sudoku Solver (Hard) 0038 - Count and Say (Easy) 0039 - Combination Sum (Medium) 0040 - Combination Sum II (Medium)

DarkRabbit的专栏 440

与OpenClaw同类性质的AI智能体框架/工具汇总(小白友好)

OpenClaw的核心定位是「开源、本地优先、可执行真实任务的AI代理」,核心价值是让AI从“聊天”落地到“动手干活”(操控电脑/服务器、处理办公/系统任务)。结合这一核心,以下是同类性质的工具/框架,按「小白易上手程度」排序,每个产品重点说明和OpenClaw的异同、核心优势及适配场景,方便小白快速区分选择。

hy行者勇哥的博客 2119

LeetCode Algorithm 0060 - Permutation Sequence (Medium)

0060 - Permutation Sequence (Medium),Related Topics: Math Backtracking

DarkRabbit的专栏 423

TGAT Python:图神经网络中的动态图算法

其中,图神经网络中的动态图算法成为了研究的热点之一。在模型的 forward 方法中,通过循环调用 TGATLayer 实例来进行图神经网络的前向传播。最终,模型返回图中节点的表示向量 output,可以用于图分类等任务。TGAT 算法的核心思想是在节点之间建立注意力连接,以捕捉节点在不同时间步之间的关系。TGAT 算法通过引入注意力机制和时间信息,从而有效地对动态图数据进行建模和分析。通过以上 Python 代码,我们可以方便地构建和训练 TGAT 模型,并在图分类任务中应用它。

2301_79366435的博客 1837

C++实现设计ATM机系统

这个示例实现了一个基本的ATM机系统,支持注册、登录、存款、取款、查询余额和保存数据等功能。当然,这只是一个简单的ATM机模拟,实际的ATM机系统需要更复杂的逻辑和更严格的安全措施。C++编写一个简单的ATM机系统,我将提供一个基本的实现示例,但由于ATM机系统的复杂性和安全性要求,这只是一个简单的模拟,不适合在实际环境中使用。试设计一简单模拟ATM机系统,系统以菜单方式工作,采用自定义函数设计各功能模块被主菜单调用,使之能提供以下基本选项。=========欢迎使用ATM=========

走向CTO的路上... 1253

LeetCode Algorithm 0046 - 0050

0046 - Permutations (Medium) 0047 - Permutations II (Medium) 0048 - Rotate Image (Medium) 0049 - Group Anagrams (Medium) 0050 - Pow(x, n) (Medium)

DarkRabbit的专栏 390

JAVA:Spring Boot 集成 Atomikos 实现分布式事务

摘要: Atomikos是一款基于JTA标准的分布式事务协调器,通过两阶段提交(2PC)协议实现跨数据库/消息系统的事务一致性,适用于金融等高要求场景。本文以Spring Boot集成Atomikos为例,演示多数据源(订单库、库存库)的分布式事务管理。核心步骤包括:引入Atomikos依赖、配置XA数据源、设置两阶段提交的MyBatis多数据源,并通过Atomikos协调全局事务,确保跨库操作原子性。代码示例涵盖配置类、YAML定义及MySQL XA数据源初始化,为分布式系统提供强一致性解决方案。

木头 338

LeetCode Algorithm 0059 - Spiral Matrix II (Medium)

0059 - Spiral Matrix II (Medium),Related Topics: Array

DarkRabbit的专栏 388

IMSL CNL 7.0.0 (x86-64)Crack

IMSL CNL 7.0.0 (x86-64)Crack intel的算法库破解文件,这是C++版本的破解文件

Camera2Demo

在Camera2 的基础上进行封装,使得Camera2一堆初始化逻辑与Activity分离,降低耦合度,完成预览拍照并保存的操作

LeetCode Algorithm 0031 - 0035

0031 - Next Permutation (Medium) 0032 - Longest Valid Parentheses (Hard) 0033 - Search in Rotated Sorted Array (Medium) 0034 - Find First and Last Position of Element in Sorted Array (Medium) 0035 - Search Insert Position (Easy)

DarkRabbit的专栏 373

LinePhone3.2.7(android端最新版本) sip客户端

SIP客户端For android:LinePhone3.2.7(最新版本),官网地址:http://www.linphone.org/

LeetCode Algorithm 0003 - Longest Substring Without Repeating Characters (Medium)

LeetCode Algorithm 0003 - Longest Substring Without Repeating Characters (Medium) Problem Link: https://leetcode.com/problems/longest-substring-without-repeating-characters/description/ Descript...

DarkRabbit的专栏 368

lwip-2.0.3

lwip是瑞典计算机科学院(SICS)的Adam Dunkels 开发的一个小型开源的TCP/IP协议栈。实现的重点是在保持TCP协议主要功能的基础上减少对RAM 的占用。

LeetCode Algorithm 0006 - ZigZag Conversion (Medium)

LeetCode Algorithm 0006 - ZigZag Conversion (Medium) Problem Link: https://leetcode.com/problems/zigzag-conversion/description/

DarkRabbit的专栏 358

LeetCode Algorithm 0026 - 0030

0026 - Remove Duplicates from Sorted Array (Easy) 0027 - Remove Element (Easy) 0028 - Implement strStr() (Easy) 0029 - Divide Two Integers (Medium) 0030 - Substring with Concatenation of All Words (Hard)

DarkRabbit的专栏 345

LeetCode Algorithm 0021 - 0025

0021 - Merge Two Sorted Lists (Easy) 0022 - Generate Parentheses (Medium) 0023 - Merge k Sorted Lists (Hard) 0024 - Swap Nodes in Pairs (Medium) 0025 - Reverse Nodes in k-Group (Hard)

DarkRabbit的专栏 341

LeetCode Algorithm 0001 - Two Sum (Easy)

LeetCode Algorithm 0001 - Two Sum (Easy) Problem Link: https://leetcode.com/problems/two-sum/description/ Description Given an array of integers, return indices of the two numbers such that the...

DarkRabbit的专栏 326

LeetCode Algorithm 0011 - 0015

0011 - Container With Most Water (Medium) 0012 - Integer to Roman (Medium) 0013 - Roman to Integer (Easy) 0014 - Longest Common Prefix (Easy) 0015 - 3Sum (Medium)

DarkRabbit的专栏 325

LeetCode Algorithm 0007 - Reverse Integer (Easy)

LeetCode Algorithm 0007 - Reverse_Integer (Easy) Problem Link: https://leetcode.com/problems/reverse-integer/description/ 文章目录LeetCode Algorithm 0007 - Reverse_Integer (Easy)DescriptionSolution C++ ...

DarkRabbit的专栏 320

算法与机器学习校招简历怎么写?本硕完整流程与范文

写好一份算法与机器学习校招简历,核心不是堆砌热门模型名称,而是用一页纸证明你能把实际问题转化为可建模的任务,并讲清数据来源、基线对比、评估指标和工程落地细节。具体落地可以按“拆解岗位需求—分组写技能—用事实改写三类经历—核验论文比赛口径—针对性排版与防追问演练”五个环节依次完成。只要每段经历都有明确的参照系和个人分工,无论本科还是研究生,都能写出经得起面试官深挖的简历。本文更新于 2026 年 11 月。

几许的博客 257

【三年面试五年模拟】2026-11-08_米哈游AI大模型算法岗面经全解析

米哈游大模型算法岗面经全解析:逐题解析9个问题,覆盖Agent推理与工具调用、轨迹和记忆、奖励排障、DPO长度偏差、学习率退火、游戏GUI Agent评测、RoPE长度扩展及DPO/PPO对比,补充状态恢复、数值算例与实验设计。

Rocky Ding相信人工智能、数据科学、商业逻辑、金融工具、终身成长以及顺应时代的潮流会赋予我们超能力。 284

FA_排序算法-冒泡排序

(相等元素相对位置不变),像水里气泡往上浮。

eillot_qian的博客 333

【三年面试五年模拟】2026-10-21_零一万物知识图谱算法实习生一面面经全解析

一万字【三年面试五年模拟】2026-10-21_零一万物知识图谱算法实习生一面面经全解析

Rocky Ding相信人工智能、数据科学、商业逻辑、金融工具、终身成长以及顺应时代的潮流会赋予我们超能力。 582
上一篇: LeetCode Algorithm 0011 - 0015
下一篇: LeetCode Algorithm 0021 - 0025
沙沙的兔子
博客等级 码龄17年 360粉丝 135原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值