zoukankan      html  css  js  c++  java
  • leetcode 【 Remove Element 】python 实现

    题目:

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

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

    代码 : oj测试通过 Runtime: 43 ms

     1 class Solution:
     2     # @param    A       a list of integers
     3     # @param    elem    an integer, value need to be removed
     4     # @return an integer
     5     def removeElement(self, A, elem):
     6         length = len(A)-1
     7         j = length
     8         for i in range(length,-1,-1):
     9             if A[i] == elem:
    10                 A[i],A[j] = A[j],A[i]
    11                 j -= 1
    12         return j+1

    思路:

    顺序便利数组元素;遇到值等于elem的,就与尾部元素交换;整个过程中维护尾部交换元素的指针位置

  • 相关阅读:
    每日日报63
    每日日报62
    每日日报61
    每日日报60
    每日日报59
    每日日报58
    el-table表格拖动排序
    vue/eslint
    $attrs $listeners
    table封装成全局组件
  • 原文地址:https://www.cnblogs.com/xbf9xbf/p/4229763.html
Copyright © 2011-2022 走看看