LeetCode | 27.移除元素


这道题的思路和26题一模一样,由于要在元素组中修改,我们可以设置一个index表示目前要修改原数组的第几位,由于遍历,访问原数组永远会在我们修改数组之前,所以不用担心数据丢失的问题,一次遍历数组,index设为0,若此时遍历到的数等于val,则跳过,若不等于val,则把这个数放进nums[index]里,再index++,直至遍历完整个数组返回index即可

python 复制代码
class Solution(object):
    def removeElement(self, nums, val):
        """
        :type nums: List[int]
        :type val: int
        :rtype: int
        """
        index = 0
        for i in range(len(nums)):
            if nums[i] != val:
                nums[index] = nums[i]
                index += 1
        return index
相关推荐
TracyCoder12333 分钟前
LeetCode Hot100(13/100)——238. 除了自身以外数组的乘积
算法·leetcode
CoderCodingNo34 分钟前
【GESP】C++五级练习题 luogu-P3353 在你窗外闪耀的星星
开发语言·c++·算法
Anastasiozzzz38 分钟前
LeetCode Hot100 215. 数组中的第K个最大元素
数据结构·算法·leetcode
让我上个超影吧39 分钟前
【力扣76】最小覆盖子串
算法·leetcode·职场和发展
近津薪荼1 小时前
优选算法——双指针5(单调性)
c++·学习·算法
2401_857683541 小时前
C++代码静态检测
开发语言·c++·算法
时艰.1 小时前
JVM 垃圾收集器(G1&ZGC)
java·jvm·算法
2401_838472511 小时前
内存泄漏自动检测系统
开发语言·c++·算法
m0_706653231 小时前
基于C++的爬虫框架
开发语言·c++·算法
diediedei2 小时前
嵌入式数据库C++集成
开发语言·c++·算法