码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2017-04-12 04:30:01      阅读:146      评论:0      收藏:0      [点我收藏+]

标签:int   结束   cat   function   等于   type   个数   his   ret   

题目:

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))

 

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

标签:int   结束   cat   function   等于   type   个数   his   ret   

原文地址:http://www.cnblogs.com/llw1121/p/6696214.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!