LeetCode OJ_题解(python):027-Remove Element ArrayEasy

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode OJ_题解(python):027-Remove Element ArrayEasy相关的知识,希望对你有一定的参考价值。

题目:

Given an array and a value, 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 in place with constant memory.

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

 

Example:
Given input array nums = [3,2,2,3]val = 3

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

 

 

给定一个数组和一个数值val,将数组中数值等于val的数去除,返回新数组的长度。不能申请额外空间,超过新数组长度部分忽略。

 


题目思路:

    由于给定的数组已经排序,那么用i,j两个下标,i记录新数组的下标,j是原来数组下标;

    如果nums[j] != val,那么nums[i] = nums[j],i,j各+ 1,最后返回 i

 


代码:

class Solution(object):
    def removeElement(self, nums, val):
        """
        :type nums: List[int]
        :type val: int
        :rtype: int
        """
        i = 0
        j = 0
        size = len(nums)
        while j <size:    #  保证循环结束
            if nums[j] == val:     #  若有与val相同的数
                j += 1
            else:
                nums[i] = nums[j]      #  将在比较的数赋给下一个数
                i += 1
                j += 1
        return i
if __name__ == "__main__":
    s = Solution()
    print(s.removeElement(nums =[3, 2, 2, 3], val = 3))

 


以上是关于LeetCode OJ_题解(python):027-Remove Element ArrayEasy的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode OJ_题解(python):001-Two Sum ArrayEasy

[LeetCode]题解(python):101-Symmetric Tree

[LeetCode]题解(python):133-Clone Graph

#OJ没有一次AC题解02-010314

leetcode oj s_06

leetcode oj s_05 最长回文子串