27. Remove Element

来源:互联网 发布:nginx ssl 编辑:程序博客网 时间:2024/06/08 20:03

题意: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
原创粉丝点击