iT邦幫忙

2021 iThome 鐵人賽

DAY 5
0

大家好,我是毛毛。ヾ(´∀ ˋ)ノ
廢話不多說開始今天的解題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 4 - Remove Duplicates from Sorted Array
下一篇
Day 6 - Search Insert Position
系列文
30天 Leetcode解題之路30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言