Day 5 - Remove Element

大家好,我是毛毛。ヾ(´∀ ˋ)ノ
废话不多说开始今天的解题Day~


27. Remove Element

Question

Given an integer array nums and an integer val, remove all occurrences of val in nums in-place. The relative order of the elements may be changed.

Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements.

Return k after placing the final result in the first k slots of nums.

Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory.
!

Custom Judge:

The judge will test your solution with the following code:

int[] nums = [...]; // Input array
int val = ...; // Value to remove
int[] expectedNums = [...]; // The expected answer with correct length.
                            // It is sorted with no values equaling val.

int k = removeElement(nums, val); // Calls your implementation

assert k == expectedNums.length;
sort(nums, 0, k); // Sort the first k elements of nums
for (int i = 0; i < actualLength; i++) {
    assert nums[i] == expectedNums[i];
}

If all assertions pass, then your solution will be accepted.


Example

Example1

Input: nums = [3,2,2,3], val = 3
Output: 2, nums = [2,2,_,_]
Explanation: Your function should return k = 2, with the first two elements of nums being 2.
It does not matter what you leave beyond the returned k (hence they are underscores).

Example2

Input: nums = [0,1,2,2,3,0,4,2], val = 2
Output: 5, nums = [0,1,4,0,3,_,_,_]
Explanation: Your function should return k = 5, with the first five elements of nums containing 0, 0, 1, 3, and 4.
Note that the five elements can be returned in any order.
It does not matter what you leave beyond the returned k (hence they are underscores).

Constraints

  • 0 <= nums.length <= 100
  • 0 <= nums[i] <= 50
  • 0 <= val <= 100

解题

题目

首先先简单的翻译一下题目
给一个整数的阵列和一个整数val,要用in-place的方式将阵列中所有的val删除。
但是有些语言可能没办法改变阵列的长度,可以将不是val的k个元素放在阵列的前k个位址,而k+1之後的位址的内容评分程序并不会管。

最後的回传值是不是val的元素个数。

这题的限制是不能使用到额外的阵列。只能透过in-place的方式修改原来的阵列。

Think

其实这题我觉得跟昨天的Remove Duplicates from Sorted Array差不多,甚至可以说是一样的。
由於in-place限制的关系,只能透过修改原来的阵列来处理。

作法大致上是这样

  • 作法跟26题大同小异。
  • Python ver. 1是因为会有index out of range的问题,想说用try&except,抓到index out of range的问题就代表做完了,直接回传阵列的长度;ver. 2的话就是不用try&except的方式去处理。
  • 同样,因为C没办法更改阵列长度,这次我是把不是val的元素跟後面最近的非val的元素交换,比到最後倒数两个,再用额外的if判断判断最後一个元素是否是val,是的话就回传最後i值,不是的话就再加上最後一个,回传i+1

Code

Python

ver. 1
class Solution:
    def removeElement(self, nums: List[int], val: int) -> int:
        if len(nums) == 0:
            return 0;

        index = 0
        while(True):
            try:
                if nums[index] == val:
                    nums.pop(index)

                else:
                    index += 1
            except:
                return len(nums)
ver. 2
class Solution:
    def removeElement(self, nums: List[int], val: int) -> int:
        if len(nums) == 0:
            return 0;

        index = 0
        length = len(nums)
        while(True):
            if nums[index] == val:
                nums.pop(index)
                length -= 1
                
                if length == index:
                    break
            else:
                if (length-1) == index:
                    break
                else:
                    index += 1
        return len(nums)

C

int removeElement(int* nums, int numsSize, int val){
    if(numsSize == 0){
        return 0;
    } else if(numsSize == 1){
        if(nums[0] == val) return 0;
        else return 1;
    }

    int tmp = 0;
    int i = 0;
    bool flag = false;
    
    for (i=0 ; i<(numsSize-1) ; i++){
        if (nums[i] == val){
            for (int j=i+1 ; j<numsSize ; j++){
                if (nums[j] != val){
                    // swap
                    tmp = nums[i];
                    nums[i] = nums[j];
                    nums[j] = tmp;
                    break;
                } else if (j == (numsSize-1) && nums[j] == val){
                    flag = true;
                    break;
                }
            }
            
        }
        if (flag){
            break;
        }
    }
    
    if (nums[numsSize-1] != val){
        return i+1;
    } else {
        return i;
    }
    
}

Result

  • Python

    • ver. 1
    • ver. 2
  • C

大家明天见/images/emoticon/emoticon29.gif


<<:  [Day - 05] - Spring Bean 运作与原理

>>:  D-10.Rails N+1 queries and kill N+1

Day26. Blue Prism取号一把罩–BP自动取得订单编号

一般订购的程序都是由下订单开始, 接着取单号为依据来分批或批次采购相关物资, 因此订单编号有举足轻重...

寝室的秘密授课(一):环境安装

「糟了!我还没有看信箱!」顶着一头蓬松乱发的诗忆匆匆的掀开被子,迅速且小心翼翼地沿着旁边的梯子往下攀...

JavaScript Day24 - Promise(1)

ES6:Promise Promise:代表一个即将成功或失败的非同步操作 会有这几状态: 搁置 (...

[Day21] CH11:刘姥姥逛物件导向的世界——类别与物件

今天开始,我们要进入物件导向的世界了,先前已经简单提过了,物件导向程序设计是一种以物件观念来设计程序...

疫後数位化

人的科技文明发展始终来自於人性 在疫情的时代当中,当所有的一切都变得不再单纯时,或是当所有的一切都变...