LeetCode Algorithm 0041 - 0045

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

LeetCode Algorithm 0041 - 0045



0041 - First Missing Positive (Hard)

Problem Link: https://leetcode.com/problems/first-missing-positive/description/

Description

Given an unsorted integer array, find the smallest missing positive integer.

Example 1:

Input: [1,2,0]
Output: 3

Example 2:

Input: [3,4,-1,1]
Output: 2

Example 3:

Input: [7,8,9,11,12]
Output: 1

Note:

Your algorithm should run in O(n) time and uses constant extra space.

Solution C++

#pragma once

#include "pch.h"

// Problem: https://leetcode.com/problems/first-missing-positive/description/

namespace P41FirstMissingPositive
{
    class Solution
    {
        public:
        int firstMissingPositive(vector<int>& nums)
        {
            // 寻找缺失的最小正整数
            // 要求 时间O(n) 与 只使用常数空间O(1)
            // 复杂度的限制,让许多方法不可行,比如排序再遍历,计数等

            if (nums.empty())
            {
                return 1;
            }

            int size = nums.size();

            for (int i = 0; i < size; i++)
            {
                // 将数字放入对应的 `下标 + 1` 中
                if (nums[i] > 0 && nums[i] <= size && nums[i] != nums[nums[i] - 1])
                {
                    swap(nums[i], nums[nums[i] - 1]);
                    i--;
                }
            }

            for (int i = 0; i < size; i++)
            {
                if (nums[i] != i + 1)
                {
                    return i + 1;
                }
            }

            return size + 1;
        }
    };
}


0042 - Trapping Rain Water (Hard)

Problem Link: https://leetcode.com/problems/trapping-rain-water/description/

Description

Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.

question 42

The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. Thanks Marcos for contributing this image!

Example:

Input: [0,1,0,2,1,0,1,3,2,1,2,1]
Output: 6

Solution C++

#pragma once

#include "pch.h"

// Problem: https://leetcode.com/problems/trapping-rain-water/description/

namespace P42TrappingRainWater
{
    class Solution
    {
        public:
        int trap(vector<int>& height)
        {
            if (height.empty() || height.size() <= 2)
            {
                return 0;
            }

            // 方法:从低值向高值移动,时间O(n)
            // 有两种方式:1、直接累加空白。 2、用面积 - 黑色方块 

#if true // 方法1
            int left = 0;
            int right = height.size() - 1;
            int result = 0;
            int leftMax = 0, rightMax = 0; // 山峰的最大值

            while (left < right)
            {
                if (height[left] < height[right])
                {
                    if (height[left] >= leftMax)
                    {
                        leftMax = height[left];
                    }
                    else
                    {
                        result += leftMax - height[left]; // 最大值 - 当前黑色方块
                    }
                    left++;
                }
                else
                {
                    if (height[right] >= rightMax)
                    {
                        rightMax = height[right];
                    }
                    else
                    {
                        result += rightMax - height[right]; // 最大值 - 当前黑色方块
                    }
                    right--;
                }
            }

            return result;
#endif // 方法1结尾

#if false // 方法2
            int left = 0;
            int right = height.size() - 1;

            // 最左端的山峰
            for (left; left < height.size() - 1; left++)
            {
                if (height[left] != 0 && height[left] > height[left + 1])
                {
                    break;
                }
            }

            // 最右端的山峰
            for (right; right > left; right--)
            {
                if (height[right] != 0 && height[right] > height[right - 1])
                {
                    break;
                }
            }
            
            // 如果只有一个山峰
            if (left == right)
            {
                return 0;
            }

            // lowIndex:低的山峰坐标
            // highIndex: 高的山峰坐标
            // dir: 从低向高的方向,1从左向右,-1从右向左
            // i:当前坐标
            int i, dir, lowIndex, highIndex;
            if (height[left] > height[right])
            {
                lowIndex = right;
                highIndex = left;
                dir = -1;
            }
            else
            {
                lowIndex = left;
                highIndex = right;
                dir = 1;
            }
            i = lowIndex + dir;

            int midCubeCount = 0; // 两个山峰之间的黑色Cube数量
            int result = 0; // 结果

            // 开始移动,当达到最高山峰时停止
            while (lowIndex != highIndex)
            {
                if (height[i] < height[lowIndex])
                {
                    if (height[i] != 0)
                    {
                        midCubeCount += height[i];
                    }
                }
                else // 如果遇到的山峰比最低的山峰(lowIndex)高
                {
                    // 长 x 宽 - 中间的黑方格
                    result += (abs(i - lowIndex) - 1) * height[lowIndex] - midCubeCount;
                    midCubeCount = 0;

                    // 如果遇到的山峰比最高的山峰(highIndex)还高,则切换方向
                    if (height[i] > height[highIndex])
                    {
                        lowIndex = highIndex;
                        highIndex = i;
                        dir = -dir;
                        i = lowIndex;
                    }
                    else
                    {
                        lowIndex = i;
                    }
                }
                i += dir;
            }

            return result;
#endif // 方法2结尾
        }
    };
}


0043 - Multiply Strings (Medium)

Problem Link: https://leetcode.com/problems/multiply-strings/description/

Description

Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2, also represented as a string.

Example 1:

Input: num1 = "2", num2 = "3"
Output: "6"

Example 2:

Input: num1 = "123", num2 = "456"
Output: "56088"

Note:

  • The length of both num1 and num2 is < 110.

  • Both num1 and num2 contain only digits 0-9.

  • Both num1 and num2 do not contain any leading zero, except the number 0 itself.

  • You must not use any built-in BigInteger library or convert the inputs to integer directly.

Solution C++

#pragma once

#include "pch.h"

// Problem: https://leetcode.com/problems/multiply-strings/description/

namespace P43MultiplyStrings
{
    class Solution
    {
        public:
        string multiply(string num1, string num2)
        {
            // 题目明确说,输入只有0-9,而且除了0之外开头都不为0。
            // 还要求不能将整个string直接转换成数字,不能使用大数库(built-in BigInteger)

            int len1 = num1.size();
            int len2 = num2.size();

            if (len1 == 0 || len2 == 0 
                || len1 >= 110 || len2 >= 110 
                || num1 == "0" || num2 == "0")
            {
                return "0";
            }

            // 每一位数字
            int maxLen = max(len1, len2);
            vector<int> num1Int = vector<int>(maxLen, 0);
            vector<int> num2Int = vector<int>(maxLen, 0);

            // 从右向左填充每个数字
            for (int i = 0; i < len1; i++)
            {
                num1Int[(maxLen - len1) + i] = num1[i] - '0';
            }
            for (int i = 0; i < len2; i++)
            {
                num2Int[(maxLen - len2) + i] = num2[i] - '0';
            }

            vector<int> resultArray = vector<int>(maxLen * 2, 0);
            for (int i2 = maxLen - 1; i2 >= 0; i2--)
            {
                for (int i1 = maxLen - 1; i1 >= 0; i1--)
                {
                    int product = num2Int[i2] * num1Int[i1];
                    int row = i2;
                    int col = i2 + i1 + 1;
                    resultArray[col] += product % 10;
                    resultArray[col - 1] += product / 10;
                    while (resultArray[col] > 9)
                    {
                        resultArray[col - 1] += resultArray[col] / 10;
                        resultArray[col] %= 10;
                        col--;
                    }
                }
            }

            string result = "";
            for (int i = 0; i < maxLen * 2; i++)
            {
                if (result == "" && resultArray[i] == 0)
                {
                    continue;
                }
                result += to_string(resultArray[i]);
            }
            return result;
        }
    };
}


0044 - Wildcard Matching (Hard)

Problem Link: https://leetcode.com/problems/wildcard-matching/description/

Description

Given an input string (s) and a pattern (p), implement wildcard pattern matching with support for '?' and '*'.

'?' Matches any single character.
'*' Matches any sequence of characters (including the empty sequence).

The matching should cover the entire input string (not partial).

Note:

  • s could be empty and contains only lowercase letters a-z.
  • p could be empty and contains only lowercase letters a-z, and characters like ? or *.

Example 1:

Input:
s = "aa"
p = "a"
Output: false
Explanation: "a" does not match the entire string "aa".

Example 2:

Input:
s = "aa"
p = "*"
Output: true
Explanation: '*' matches any sequence.

Example 3:

Input:
s = "cb"
p = "?a"
Output: false
Explanation: '?' matches 'c', but the second letter is 'a', which does not match 'b'.

Example 4:

Input:
s = "adceb"
p = "*a*b"
Output: true
Explanation: The first '*' matches the empty sequence, while the second '*' matches the substring "dce".

Example 5:

Input:
s = "acdcb"
p = "a*c?b"
Output: false

Solution C++

#pragma once

#include "pch.h"

// Problem: https://leetcode.com/problems/wildcard-matching/description/

namespace P44WildcardMatching
{
    class Solution
    {
        private:
        static const char k_Letter = '?';
        static const char k_Any = '*';

        public:
        bool isMatch(string s, string p)
        {
            if (p.empty())
            {
                return s.empty() ? true : false;
            }

            if (p == "*")
            {
                return true;
            }

            if (s.empty())
            {
                return false;
            }

            int sSize = s.size();
            int pSize = p.size();
            int anyIndex = -1;
            int matchIndex = 0;
            int j = 0;
            for (int i = 0; i < sSize; i++)
            {
                if (j < pSize && (s[i] == p[j] || p[j] == k_Letter))
                {
                    j++;
                }
                else if (j < pSize && p[j] == k_Any)
                {
                    anyIndex = j;
                    matchIndex = i;
                    i--;
                    j++;
                }
                else if (anyIndex != -1)
                {
                    j = anyIndex + 1;
                    matchIndex++;
                    i = matchIndex - 1;
                }
                else
                {
                    return false;
                }
            }

            while (j < pSize && p[j] == k_Any)
            {
                j++;
            }

            return j == pSize;
        }
    };
}


0045 - Jump Game II (Hard)

Problem Link: https://leetcode.com/problems/jump-game-ii/description/

Description

Given an array of non-negative integers, you are initially positioned at the first index of the array.

Each element in the array represents your maximum jump length at that position.

Your goal is to reach the last index in the minimum number of jumps.

Example:

Input: [2,3,1,1,4]
Output: 2
Explanation: The minimum number of jumps to reach the last index is 2.
    Jump 1 step from index 0 to 1, then 3 steps to the last index.

Note:

You can assume that you can always reach the last index.

Solution C++

#pragma once

#include "pch.h"

// Problem: https://leetcode.com/problems/jump-game-ii/description/

namespace P45JumpGameII
{
#if true // 贪心算法
    class Solution
    {
        public:
        int jump(vector<int>& nums)
        {
            if (nums.empty() || nums.size() == 1)
            {
                return 0;
            }

            // 题目已经说明输入参数永远有解

            // 以官方例子[2,3,1,1,4]来说
            // nums[0] = 2 , 可以跳 [1, 2]
            // nums[1] = 3 , 可以跳 [1, 2, 3]
            // nums[2] = 1 , 可以跳 [1]
            // nums[3] = 1 , 可以跳 [1]
            // nums[4] = 4
            // 每次能跳的最大距离,只需要跳一次
            //  例如 从nums[1] 调到 num[4] 
            //  已经涵盖了 nums[2] 与 nums[3] 能跳的距离。

            int result = 0;
            int curIndex = 0;
            int largest = 0;
            for (int i = 0; i < nums.size() - 1; i++)
            {
                largest = max(largest, i + nums[i]);
                if (i == curIndex)
                {
                    result++;
                    curIndex = largest;
                }

                if (curIndex >= nums.size() - 1)
                {
                    break;
                }
            }

            return result;
        }
    };
#endif

#if false // 递归穷举
    class Solution
    {
        public:
        int jump(vector<int>& nums)
        {
            if (nums.empty() || nums.size() == 1)
            {
                return 0;
            }

            // 题目已经说明输入参数永远有解

            int result = INT_MAX;
            vector<int> path;
            jumping(nums, nums.size(), path, 0, result);
            return result;
        }

        private:
        void jumping(vector<int>& nums, int size, vector<int>& path, int startIndex, int& result)
        {
            if (nums[startIndex] == 0)
            {
                return;
            }

            for (int i = 1; i <= nums[startIndex]; i++)
            {
                path.push_back(startIndex);
                if (startIndex + i == size - 1)
                {
                    result = min(result, (int)path.size());
                }
                else if (startIndex + i < size - 1)
                {
                    jumping(nums, size, path, startIndex + i, result);
                }
                path.pop_back();
            }
        }
    };
#endif
}


VS2019中C++动态链接库(DLL)的创建与调用 VS2019中C++动态链接库(DLL)的创建与调用,及一些进阶技巧。 阅读详情

相关推荐

机器人开发路线

通过这个路线图,你可以在6个月内完成从原型到试产的全流程。建议初期采用敏捷开发模式,每两周迭代一个核心功能模块。在硬件集成遇到瓶颈时,推荐参考。

woody218的博客 747

LeetCode Algorithm部分

LeetCode Algorithm部分.004【004】 Search a 2D Matrix II Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).

mattmu的博客 430

GoDaddy域名解析 到 阿里云域名DNS

一:登录GODaddy,点击“个人中心”,然后点击“管理域名” 二:域名解析 第一种:直接解析到对应的服务器 添加一个,类型默认A,主机填写二级域名前缀(image.主域名),指向填写目标服务器ip即可(注意目标服务器80端口是否开放) 第二种:将主域名dns转到阿里云域名下 三:若要修给为阿里云解析服务器,要做以下修改,点击“更改” 点击更改后出现如下页面,此时需要到阿里云官网云解析DNS下添加域名解析 四:阿里云添加域名解析...

xiaolinzi176的博客 6713

LeetCode Algorithm Menu (算法目录)

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

DarkRabbit的专栏 612

Python调用Google Trends官方数据接口实战指南

Google Trends作为全球最权威的搜索热度分析工具,其数据本质是公开、结构化、可编程访问的时序指标,而非需爬取的网页内容。其底层基于标准HTTP协议与JSON API交互,核心原理在于复现用户浏览器行为——通过/explore接口获取token,再凭token请求/widgetdata/multiline等端点获取归一化(0-100)时间序列数据。该技术路径规避了Selenium渲染依赖与非官方库的脆弱性,具备高稳定性、易调试、可监控等工程优势,广泛应用于竞品监测、内容选题验证、地域营销策略制定等业

weixin_29789925的博客 427

PLC编程标准之争:IEC61131与IEC61499核心区别与选型指南

在工业自动化领域,PLC编程长期依赖IEC61131标准,它定义了梯形图、结构化文本等语言,通过周期扫描机制保证确定性执行。然而,随着工业4.0和分布式控制场景的兴起,IEC61499以事件驱动模型打破传统范式,让功能块能跨设备协同,实现更灵活的柔性产线和模块化系统。理解两者在程序结构、数据交互、部署方式和实时性上的差异,是选型与工程落地的关键。本文从基础概念出发,剖析执行模型与架构演进,结合一线调试经验,帮助工程师在传统PLC与下一代标准之间做出理性决策。

weixin_27014595的博客 275

LeetCode Algorithm 0051 - 0055

0051 - N-Queens (Hard), 0052 - N-Queens II (Hard), 0053 - Maximum Subarray (Easy), 0054 - Spiral Matrix (Medium), 0055 - Jump Game (Medium)

DarkRabbit的专栏 293

Matlab双目相机标定

1 概述 现在有许多双目相机在出厂时就已经标定好了,用户拿到手后可以直接使用,例如Intel Realsense系列。但是有些相机出厂的时候并没有完成标定工作,因而这个时候就需要我们自己来标定。由于笔者曾改装过一个双目相机,最远可以测至50m,因此有一定的心得体会想给大家分享一下。本文主要介绍双目相机标定的整个过程,以及导出标定数据的方法。 相机标定主要分为手动标定和自动标定,手动标定比较繁琐,这里主要介绍基于matlab工具箱的自动标定方式来对双目相机进行标定。具体的相关标定细节也可以参照这篇博客:m

weixin_46133643的博客 2万+

leetcode algo NO.171 python solution

class Solution: def titleToNumber(self, s): """ :type s: str :rtype: int """ sum = 0 for i in range(len(s)): sum += (ord(s[-(i+1)])-64) ...

Peter-Chou的博客 256

JetLinks社区版VS企业版:手把手教你用PostgreSQL+Redis搭建物联网中台(Win7实测)

本文详细对比了JetLinks社区版与企业版的核心差异,并提供了在Windows 7系统上,使用PostgreSQL和Redis搭建物联网中台的完整部署教程。文章深入解析了从环境准备、后端服务构建到前端部署的每一步,为开发者在资源有限环境下构建高性价比物联网平台提供了清晰的实战指南。

w1x2y3的博客 315

一文掌握 MongoDB 详细安装与配置(Windows / Linux / macOS 全平台)

本文详细介绍了MongoDB社区版7.0+在Windows、Linux和macOS三大操作系统上的完整安装、配置与安全加固流程。主要内容包括:各平台推荐安装方式(Windows使用MSI安装包、Linux通过官方仓库、macOS通过Homebrew)、基本配置参数说明、服务启动方法以及关键安全措施(如创建管理员用户和启用身份验证)。文章还提供了系统最低要求、下载地址、数据目录设置建议以及生产环境使用注意事项,适合开发、测试及生产环境部署参考。

数据知道的博客 6753

LeetCode Algorithm

刷lc不为其他,只为工程能力扩展与思维提升! 请看github:leetCode   Given an array of integers, return indices of the two numbers such that they add up to a specific target. You may assume that each input would have exact...

MachineLP的专栏 362

目标跟踪与视频时序分析基础

两帧均有目标,却因快速移动导致检测框无重叠,仅靠交并比(IoU)无法维持身份关联。本文通过手算与纯Python实现最小跟踪流程,揭示IoU仅为位置线索,不能应对快速位移或遮挡。实验表明,即使目标真实存在,低重叠也会触发新编号。强调跟踪需结合运动预测、外观特征与阈值验证,避免误判。

Mr数据杨 2353

LeetCode 算法学习指南

本文来自微信公众号:labuladong 之前发的那篇关于 框架性思维 的文章,我也发到了不少其他圈子,受到了大家的普遍好评,这一点我真的没想到,首先感谢大家的认可,我会更加努力,写出通俗易懂的算法文章。 有很多朋友问我数据结构和算法到底该怎么学,尤其是很多朋友说自己是「小白」,感觉这些东西好难啊,就算看了之前的「框架思维」,也感觉自己刷题乏力,希望我能聊聊我从一个非科班小白一路是怎么学过来的。 ...

fdl123456的博客 7619

RU DOS版、EFI版32bit/64bit BIOS常用工具

DOS版、EFI版的RU工具,可用来查看IO、MEM、PCI、SMBIOS等资源。亲测在EFI SHELL下可用。

数学建模模型总结

这是本人在两年内准备参加数学建模竞赛搜集到的模型资料,已经经过了本人的筛选和整理,希望能够对准备参加数学建模竞赛的学弟学妹们提供一些帮助!

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

全球国家地区城市数据

MySQL全球国家地区城市数据报。。。。。。。。。。。。

LeetCode Algorithm 0060 - Permutation Sequence (Medium)

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

DarkRabbit的专栏 423

vb 6.0并口开发操作实例

vb6并口开发,简体中文,试例内有inpout32.dll动态链接库

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

LeetCode Algorithm 0059 - Spiral Matrix II (Medium)

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

DarkRabbit的专栏 388

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

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

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
上一篇: LeetCode Algorithm 0036 - 0040
下一篇: LeetCode Algorithm 0046 - 0050
沙沙的兔子
博客等级 码龄17年 360粉丝 135原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值