LeetCode OJ_题解(python):027-Remove Element 【Array】【Easy】

题目:

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))
原文地址:https://www.cnblogs.com/llw1121/p/6696214.html