zoukankan      html  css  js  c++  java
  • [leetcode]Remove Element @ Python

    原题地址:https://oj.leetcode.com/problems/remove-element/

    题意:

    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.

    解题思路:去掉数组中等于elem的元素,返回新的数组长度,数组中的元素不必保持原来的顺序。使用头尾指针,头指针碰到elem时,与尾指针指向的元素交换,将elem都换到数组的末尾去。

    代码:

    class Solution:
        # @param    A       a list of integers
        # @param    elem    an integer, value need to be removed
        # @return an integer
        # clrs qsort
        def removeElement(self, A, elem):
            j = len(A)-1
            for i in range(len(A) - 1, -1, -1):
                if A[i] == elem:
                    A[i], A[j] = A[j], A[i]
                    j -= 1
            return j+1
  • 相关阅读:
    JAVA多线程之AQS
    LRU算法
    JAVA设计之SPI
    JAVA多线程之CAS
    操作系统之中断处理
    计算机领域思想
    操作系统之I/O
    操作系统之虚拟内存
    Mysql事务原理
    Mysql添加索引
  • 原文地址:https://www.cnblogs.com/zuoyuan/p/3779848.html
Copyright © 2011-2022 走看看