zoukankan      html  css  js  c++  java
  • 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))
  • 相关阅读:
    解决IE6浏览器下position:fixed固定定位问题
    CSS中overflow:hidden在ie6、ie7无效不能隐藏解决办法
    liunx 中删除export设置的环境变量
    文件操作
    集合操作
    三级菜单
    字典操作
    字符串操作
    购物车程序
    列表操作
  • 原文地址:https://www.cnblogs.com/llw1121/p/6696214.html
Copyright © 2011-2022 走看看