27. Remove Element

题意: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.

思路:这题思路和 26. Remove Duplicates from Sorted Array 基本差不多。但是现在要去除的不是重复数,而是固定数,思路就很多了,下面方法1是我自己的解法,其他的都是别人,但是他们的思路要明显比我这个简单。

方法一:

class Solution(object):
    def removeElement(self, nums, val):
        """
        :type nums: List[int]
        :type val: int
        :rtype: int
        """
        i = 0
        for j in xrange(len(nums)):
            nums[i] = nums[j]
            if nums[i] != val:
                i += 1
            else:
                while nums[j] == val and j<len(nums)-1:
                    j += 1
        # print nums
        return i

这个是基础的方法,利用双指针来求解。

方法二:

class Solution:
    def removeElement(self, A, elem):
        i, last = 0, len(A) - 1
        while i <= last:
            if A[i] == elem:
                A[i], A[last] = A[last], A[i]
                last -= 1
            else:
                i += 1
        return last + 1

这个方法就很巧妙了,题目中说了超出新数组长度的部分不考虑,所以直接把val直接和末端的数调换就好了。

方法三:

int removeElement(int* nums, int numsSize, int val) {
    int i, j;
    for(i = j = numsSize - 1; i >= 0; i--)
        if(nums[i] == val && i != j--) nums[i] = nums[j+1] ;
    return j+1;
}

这是一段C++的代码,但是实在在太厉害了,所以放上来,这个方法从末端开始计算,这里最巧妙的就是&&i!=j–这句话,而i!=j这句话是用来对末端开始的几个val进行忽视的,其他的就需要自己体会了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值