zoukankan      html  css  js  c++  java
  • lintcode:Remove Element 删除元素

    题目:

    删除元素

    给定一个数组和一个值,在原地删除与值相同的数字,返回新数组的长度。

    元素的顺序可以改变,并且对新的数组不会有影响。

     样例

    给出一个数组 [0,4,4,0,0,2,4,4],和值 4

    返回 4 并且4个元素的新数组为[0,0,0,2]

    解题:

    Java程序:

    public class Solution {
        /** 
         *@param A: A list of integers
         *@param elem: An integer
         *@return: The new length after remove
         */
        public int removeElement(int[] A, int elem) {
            // write your code here
            int count = A.length;
            // for(int i=0;i<count;i++)
            int i=0;
            while(i<count){
                if(A[i]==elem){
                    
                    for(int j=i;j<count-1;j++)
                        A[j] = A[j+1];
                    count--;
                }else
                    i++;
            }
            return count;
        }
    }
    View Code

    总耗时: 1782 ms

    这样竟然也可以通过,这里时间复杂度是O(n2),同时你会发现,只是把数组移位了,没有真正的删除,但是这里的测试结果是输出正确情况下的长度。。。。
    还有个问题就是,测试用例太少了。。。。

    官当答案也是这样搞的。。。

    Python程序:

    class Solution:
        """
        @param A: A list of integers
        @param elem: An integer
        @return: The new length after remove
        """
        def removeElement(self, A, elem):
            # write your code here
            i = 0
            ALen = len(A)
            while i<ALen:
                if A[i]==elem:
                    ALen-=1
                    del A[i]
                else:
                    i+=1
            return ALen
    View Code

    总耗时: 286 ms

    Python list 可以直接删除指定index下标的元素

  • 相关阅读:
    UVA 254 Towers of Hanoi
    UVA 701 The Archeologists' Dilemma
    UVA 185 Roman Numerals
    UVA 10994 Simple Addition
    UVA 10570 Meeting with Aliens
    UVA 306 Cipher
    UVA 10160 Servicing Stations
    UVA 317 Hexagon
    UVA 10123 No Tipping
    UVA 696 How Many Knights
  • 原文地址:https://www.cnblogs.com/theskulls/p/4868297.html
Copyright © 2011-2022 走看看