LeetCode Algorithm 0026 - 0030

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

LeetCode Algorithm 0026 - 0030



0026 - Remove Duplicates from Sorted Array (Easy)

Problem Link: https://leetcode.com/problems/remove-duplicates-from-sorted-array/description/

Description

Given a sorted array nums, remove the duplicates in-place such that each element appear only once and return the new length.

Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.

Example 1:

Given nums = [1,1,2],

Your function should return length = 2, 
with the first two elements of nums being 1 and 2 respectively.

It doesn't matter what you leave beyond the returned length.

Example 2:

Given nums = [0,0,1,1,1,2,2,3,3,4],

Your function should return length = 5, with the first five 
elements of nums being modified to 0, 1, 2, 3, and 4 respectively.

It doesn't matter what values are set beyond the returned length.

Clarification:

Confused why the returned value is an integer but your answer is an array?

Note that the input array is passed in by reference , which means modification to the input array will be known to the caller as well.

Internally you can think of this:

// nums is passed in by reference. (i.e., without making a copy)
int len = removeDuplicates(nums);

// any modification to nums in your function would be known by the caller.
// using the length returned by your function, it prints the first len elements.
for (int i = 0; i < len; i++) {
    print(nums[i]);
}

Solution C++

#pragma once

#include "pch.h"

// Problem: https://leetcode.com/problems/remove-duplicates-from-sorted-array/description/

namespace P26RemoveDuplicatesFromSortedArray
{
    class Solution
    {
        public:
        int removeDuplicates(vector<int>& nums)
        {
            if (nums.empty())
            {
                return 0;
            }

            unordered_set<int> numSet;
            int length = 0;
            for (vector<int>::iterator it = nums.begin(); it != nums.end();)
            {
                if (numSet.find(*it) == numSet.end())
                {
                    numSet.insert(*it);
                    length++;
                    it++;
                }
                else
                {
                    nums.erase(it);
                }
            }

            return length;
        }
    };
}


0027 - Remove Element (Easy)

Problem Link: https://leetcode.com/problems/remove-element/description/

Description

Given an array nums and a value val, remove all instances of that value in-place and return the new length.

Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.

The order of elements can be changed. It doesn’t matter what you leave beyond the new length.

Example 1:

Given nums = [3,2,2,3], val = 3,

Your function should return length = 2, 
with the first two elements of nums being 2.

It doesn't matter what you leave beyond the returned length.

Example 2:

Given nums = [0,1,2,2,3,0,4,2], val = 2,

Your function should return length = 5, 
with the first five elements of nums containing 0, 1, 3, 0, and 4.

Note that the order of those five elements can be arbitrary.

It doesn't matter what values are set beyond the returned length.

Clarification:

Confused why the returned value is an integer but your answer is an array?

Note that the input array is passed in by reference, which means modification to the input array will be known to the caller as well.

Internally you can think of this:

// nums is passed in by reference. (i.e., without making a copy)
int len = removeElement(nums, val);

// any modification to nums in your function would be known by the caller.
// using the length returned by your function, it prints the first len elements.
for (int i = 0; i < len; i++) {
    print(nums[i]);
}

Solution C++

#pragma once

#include "pch.h"

// Problem: https://leetcode.com/problems/remove-element/description/

namespace P27RemoveElement
{
    class Solution
    {
        public:
        int removeElement(vector<int>& nums, int val)
        {
            if (nums.empty())
            {
                return 0;
            }

            int length = 0;
            for (vector<int>::iterator it = nums.begin(); it != nums.end();)
            {
                if (*it == val)
                {
                    nums.erase(it);
                }
                else
                {
                    it++;
                    length++;
                }
            }

            return length;
        }
    };
}


0028 - Implement strStr() (Easy)

Problem Link: https://leetcode.com/problems/implement-strstr/description/

Description

Implement strStr().

Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

Example 1:

Input: haystack = "hello", needle = "ll"
Output: 2

Example 2:

Input: haystack = "aaaaa", needle = "bba"
Output: -1

Clarification:

What should we return when needle is an empty string? This is a great question to ask during an interview.

For the purpose of this problem, we will return 0 when needle is an empty string. This is consistent to C’s strStr() and Java’s indexOf().

Solution C++

#pragma once

#include "pch.h"

// Problem: https://leetcode.com/problems/implement-strstr/description/

namespace P28Implement_strStr
{
    class Solution
    {
        public:
        int strStr(string haystack, string needle)
        {
            if (needle.empty())
            {
                return 0;
            }

            if (haystack.empty() || haystack.size() < needle.size())
            {
                return -1;
            }

            int needleSize = needle.size();

            for (size_t i = 0; i <= haystack.size() - needleSize; i++)
            {
                if (haystack[0] == needle[0] && haystack.substr(i, needleSize) == needle)
                {
                    return i;
                }
            }

            return -1;
        }
    };
}


0029 - Divide Two Integers (Medium)

Problem Link: https://leetcode.com/problems/divide-two-integers/description/

Description

Given two integers dividend and divisor, divide two integers without using multiplication, division and mod operator.

Return the quotient after dividing dividend by divisor.

The integer division should truncate toward zero.

Example 1:

Input: dividend = 10, divisor = 3
Output: 3

Example 2:

Input: dividend = 7, divisor = -3
Output: -2

Note:

  • Both dividend and divisor will be 32-bit signed integers.
  • The divisor will never be 0.
  • Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [ − 2 31 , 2 31 − 1 ] [-2^{31}, 2^{31} - 1] [−231,231−1]. For the purpose of this problem, assume that your function returns 2 31 − 1 2^{31} - 1 231−1 when the division result overflows.

Solution C++

#pragma once

#include "pch.h"

// Problem: https://leetcode.com/problems/divide-two-integers/description/

namespace P29DivideTwoIntegers
{
    class Solution
    {
        public:
        int divide(int dividend, int divisor)
        {
            // 题目要求,只能使用`有符号32位整数`,
            // 所以不能使用 unsigned, long long 和 size_t 等等类型,只能使用类型 int32_t 。
            // 要注意 C++ 在不同环境中 int 的取值范围,这里假设为 负的2的31次方 到 2的31次方减1 。
            // 还要求不能使用 *, / 和 % 。

            // error,题目已经明确输入的 divisor 不会为 0,但还是判断一下
            if (divisor == 0)
            {
                return -1;
            }

            if (dividend == 0
                || (dividend > 0 && dividend < divisor)
                || (dividend < 0 && dividend > divisor))
            {
                return 0;
            }

            if (dividend == divisor)
            {
                return 1;
            }

            if (dividend == -divisor)
            {
                return -1;
            }

            int sign1, sign2, abs1, neg1, abs2, neg2;

            if (dividend > 0)
            {
                sign1 = 1;
                abs1 = dividend;
                neg1 = -dividend;
            }
            else
            {
                sign1 = -1;
                abs1 = -dividend;
                neg1 = dividend;
            }

            if (divisor > 0)
            {
                sign2 = 1;
                abs2 = divisor;
                neg2 = -divisor;
            }
            else
            {
                sign2 = -1;
                abs2 = -divisor;
                neg2 = divisor;
            }

            // INT_MIN = 1000 0000 0000 0000 0000 0000 0000 0000
            // INT_MAX = 0111 1111 1111 1111 1111 1111 1111 1111
            const int maxth = 1 << 30; // 0100 0000 0000 0000 0000 0000 0000 0000
            int result = 0;

            // 二进制
            // 乘法举例:10 * 3
            //  1010 * 0011 = 1010 * (0010 + 0001) 
            //              = 1010 << 1 + 1010 << 0 (0010 = 1 << 1, 0001 = 1 << 0)
            //              = 0001 0100 + 1010 = 0001 1110 = 30
            // 除法举例:10 / 3
            //  1010 / 0011 = 1010 / (0010 + 0001)
            //
            //  按乘法反推:1010 >= (0011 << n1) + (0011 << n2)
            //      1010 >= (0011 << n1) => n1 最大能为 1
            //      
            //      1010 - (0011 << n1) >= (0011 << n2) => (n1 = 1)
            //      1010 - 110 = 100    >= (0011 << n2) => n2 最大能为 0
            //
            //      result = (1 << n1) + (1 << n2) = 0010 + 0001 = 0011 = 3
            while (neg1 <= neg2)
            {
                int d, quotient;
                for (d = abs2, quotient = 1;; d <<= 1, quotient <<= 1)
                {
                    if ((d & maxth) != 0 || -(d << 1) < neg1)
                    {
                        break;
                    }
                }

                neg1 += d;
                result -= quotient;

                if (result == INT_MIN) // INT_MIN / -1 = INT_MAX + 1 ,强制让它等于 INT_MAX
                {
                    if (sign1 == sign2)
                    {
                        result += 1;
                    }
                    break;
                }
            }

            return sign1 == sign2 ? -result : result;
        }
    };
}


0030 - Substring with Concatenation of All Words (Hard)

Problem Link: https://leetcode.com/problems/substring-with-concatenation-of-all-words/description/

Description

You are given a string, s , and a list of words, words , that are all of the same length. Find all starting indices of substring(s) in s that is a concatenation of each word in words exactly once and without any intervening characters.

Example 1:

Input:
  s = "barfoothefoobarman",
  words = ["foo","bar"]
Output: [0,9]
Explanation: Substrings starting at index 0 and 9 are "barfoor" and "foobar" respectively.
The output order does not matter, returning [9,0] is fine too.

Example 2:

Input:
  s = "wordgoodstudentgoodword",
  words = ["word","student"]
Output: []

Solution C++

#pragma once

#include "pch.h"

// Problem: https://leetcode.com/problems/substring-with-concatenation-of-all-words/description/

namespace P30SubstringWithConcatenationOfAllWords
{
    class Solution
    {
        public:
        vector<int> findSubstring(string s, vector<string>& words)
        {
            // 没有字符串或单词
            if (s.empty() || words.empty())
            {
                return vector<int>();
            }

            // 单词计数
            unordered_map<string, int> countMap;
            for (size_t i = 0; i < words.size(); i++)
            {
                if (words[i].size() == 0)
                {
                    continue;
                }
                countMap[words[i]] += 1;
            }

            // 开始计算
            int lenStr = s.size(); // 字符串长度
            int numWords = words.size(); // 单词数量
            int lenWord = words[0].size(); // 单词长度

            vector<int> result;
            for (int i = 0; i <= lenStr - numWords * lenWord; i++)
            {
                unordered_map<string, int> useCountMap;
                int j = 0;
                for (j; j < numWords; j++)
                {
                    string word = s.substr(i + j * lenWord, lenWord); // 分割字符串
                    if (countMap.find(word) != countMap.end())
                    {
                        useCountMap[word] += 1;
                        if (useCountMap[word] > countMap[word])
                        {
                            break;
                        }
                    }
                    else // 不存在
                    {
                        break;
                    }
                }

                if (j == numWords)
                {
                    result.push_back(i);
                }
            }

            return result;
        }
    };
}


conda install出现CondaValueError: Malformed version string invalid character(s)解决方案 本文主要介绍了conda install出现Solving environment:failed、CondaValueError: Malformed version string invalid character(s),希望能对新手有所帮助。 文章目录 1. 问题描述 2. 解决方案 2.1 步骤一 2.2 步骤二 2.3 步骤三 阅读详情

相关推荐

【语音识别入门】特征提取(Python完整代码)

给定一段音频,请提取12维MFCC特征和23维FBank,阅读代码预加重、分帧、加窗部分,完善作业代码中FBank特征提取和MFCC特征提取部分,并给出最终的FBank特征和MFCC特征,存储在纯文本中,用默认的配置参数,无需进行修改。抽样时频率不够高,抽样出来的点既代表了信号中的低频信号的样本值,也同时代表高频信号样本值,在信号重建的时候,高频信号被低频信号代替,两种波形完全重叠在一起,形成严重失真。DFT得到了每个频带上信号的能量,但是人耳对频率的感知不是等间隔的,近似于对数函数。

weixin_51293984的博客 1万+

LeetCode算法系列:27. Remove Element

题目描述: Given an array nums and a value val, remove all instances of that value in-place and return the new length. Do not allocate extra space for another array, you must do this by modifying the inp...

Efan_W的博客 253

线性模型:AR、MA、ARMA、ARMAX、ARX、ARARMAX、OE、BJ等

线性模型:AR、MA、ARMA、ARMAX、ARX、ARARMAX、OE、BJ等

zephyr_wang的博客 1万+

LeetCode Algorithm Menu (算法目录)

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

DarkRabbit的专栏 612

仿真每日一练 | Workbench下薄板疲劳分析

今天给大家介绍Workbench下薄板疲劳分析,采用稳态分析模块进行评估。完成求解后,插入疲劳工具,同时插入对应的寿命进行查看,如图7和图8所示。采用稳态分析模块,导入几何模型,效果如图1。添加固定约束与扭矩,同时添加转速如图4所示。主要包括7要素,对应的类型见图2。求解完成后查看应力,如图6所示。1-1-3、有限元系统模型构建。1-2-1、加载条件/边界条件。1-1-1、几何模型构建。1-1-2、材料定义。1-2-2、求解设置。1-3-1、查看结果。1-3-2、评估结果。1-3-3、修正结果。

ansysxuexizhe的博客 1076

Apk脱壳圣战之---脱掉“梆梆加固”的保护壳

一、前言 现如今Android用户的安全意识不是很强,又有一些恶意开发者利用应用的名字吸引眼球,包装一个恶意锁机收费的应用,在用户被骗的安装应用之后,立马手机锁机,需要付费方可解锁。这样的恶意软件是非常让人痛恨的。所以本文就用一个案例来分析如何破解这类应用,获取解锁密码,让被骗的用户可以找回爽快! 二、分析软件锁机原理 本文用的是一款叫做:安卓性能激活.apk,关于样本apk文件后面会...

尼古拉斯.赵四的博客 5074

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的专栏 440

Apollo&Carla联合仿真基本操作

基于UE4开发的开源无人驾驶仿真器PythonAPI自动驾驶传感器(还有理想化的collision detection传感器)用于规划和控制的快速仿真地图生成交通场景(open scenario)仿真ROS集成自动驾驶baseline0.9.15新特性新的车型以及地图基于Omniverse的素材导入基于OSM的三维场景生成。

SLAM小土堆 3807

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

C# Modbus协议全解析 万字长文|RTU/TCP/UDP完整实战(寄存器映射+多从站组网+NModbus4工业级代码)

你做C#工业上位机开发,Modbus协议是绕不开的终极核心,没有之一!Modbus是由施耐德在1979年发布的工业级串行通信协议,经过40余年的发展,已经成为工业自动化领域的通用标准协议—— 小到温湿度传感器、智能电表、小型PLC,大到变频器、伺服驱动器、DCS集散控制系统,99%的工业设备都原生支持Modbus协议(RTU/TCP二选一,多数全支持)。很多开发者觉得Modbus「知识点杂、协议分支多、组网难」,本质是只掌握了零散的读写代码,没吃透。

这里只有干货:从 Modbus 通信到 MES 对接,从 YOLO 训练到工控机部署,带你搞定工业软件开发全流程。 1069

YOLOv5 实现 10 种热力图可视化方式教程 | GradCAM XGradCAM ScoreCAM LayerCAM HiResCAM EigenCAM......

10 种热力图可视化方法 ,总有一款适合你

Coding... 5577

LeetCode Algorithm 0060 - Permutation Sequence (Medium)

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

DarkRabbit的专栏 423

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

廖雪峰Python教程[完整版]

廖雪峰的python教程整理的,已经排好版了,而且还是完整的,适合小白

STM32F407中文手册

STM32f407中文手册 本参考手册面向应用开发人员,提供有关使用 STM32F405xx/07xx、STM32F415xx/17xx、 STM32F42xxx 和 STM32F43xxx 微控制器存储器与外设的完整信息。STM32F405xx/07xx、STM32F415xx/17xx、STM32F42xxx 和 STM32F43xxx 构成一个微 控制器系列,各产品具有不同的存储器大小、封装和外设。有关订购信息以及器件的机械与电气特性,请参见数据手册。有关 ARM Cortex™-M4F 内核的信息,请参见《Cortex™-M4F 技术参考手册》。

LeetCode Algorithm 0059 - Spiral Matrix II (Medium)

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

DarkRabbit的专栏 388

visio安装包

Microsoft Office Visio 是一款专业的制图软件。利用经过更新的形状、协作工具和数据链接图表,创建专业级图表以简化复杂的信息。

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的专栏 372

pscad IEEE标准系统搭建说明

pscad IEEE标准系统搭建说明,包含典型的IEEE 9节点、14节点、30节点、39节点和118节点系统。内含标准测试系统的原始数据和潮流结果。

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的专栏 357

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 月。

几许的博客 255

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

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

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

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

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

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

FA_排序算法-冒泡排序

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

eillot_qian的博客 331
上一篇: LeetCode Algorithm 0021 - 0025
下一篇: LeetCode Algorithm 0031 - 0035
沙沙的兔子
博客等级 码龄17年 360粉丝 135原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值