アルゴリズム:スペースを追加せずに配列内の数値を削除します27.要素を削除します

:LeetCodeの完全なコレクションについては、を参照してくださいLeetCode Githubのコレクション

トピック

27.要素の削除
配列numsと値valを指定して、その値のすべてのインスタンスをインプレースで削除し、新しい長さを返します。

別の配列に余分なスペースを割り当てないでください。O(1)の余分なメモリを使用して入力配列をインプレースで変更することによってこれを行う必要があります。

要素の順序は変更できます。新しい長さを超えて何を残すかは問題ではありません。

明確化:

戻り値が整数であるのに、答えが配列である理由がわかりませんか?

入力配列は参照によって渡されることに注意してください。これは、入力配列への変更が呼び出し元にも認識されることを意味します。

内部的には、これについて考えることができます。

// nums is passed in by reference. (i.e., without making a copy)
int len = removeElement(nums, val);

// any modification to nums in your function would be known by the caller.
// using the length returned by your function, it prints the first len elements.
for (int i = 0; i < len; i++) {
    
    
    print(nums[i]);
}

例1:

Input: nums = [3,2,2,3], val = 3
Output: 2, nums = [2,2]
Explanation: Your function should return length = 2, with the first two elements of nums being 2.
It doesn't matter what you leave beyond the returned length. For example if you return 2 with nums = [2,2,3,3] or nums = [2,2,0,0], your answer will be accepted.

例2:

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 length = 5, with the first five elements of nums containing 0, 1, 3, 0, and 4. Note that the order of those five elements can be arbitrary. It doesn't matter what values are set beyond the returned length.

制約:

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

1.ビットごとのコピーソリューション

class Solution {
    
    
    public int removeElement(int[] nums, int val) {
    
    
        // check edge
        if (nums == null || nums.length == 0) {
    
    
            return 0;
        }
        int index = 0;
        for(int i = 0; i < nums.length; i++) {
    
    
            if (nums[i] != val) {
    
    
                nums[index] = nums[i];
                index++;
            }
        }
        
        return index;
    }
}

2.最初と最後が高効率ソリューションに変更したい

class Solution {
    
    
    public int removeElement(int[] nums, int val) {
    
    
        // check edge
        if (nums == null || nums.length == 0) {
    
    
            return 0;
        }
        int index = 0;
        int n = nums.length - 1;
        while (index <= n) {
    
    
            if (nums[index] == val) {
    
    
                nums[index] = nums[n];
                nums[n] = val;
                n--;
            } else {
    
    
                index++;
            }
        }
        
        return index;
    }
}

おすすめ

転載: blog.csdn.net/zgpeace/article/details/113882894