問題は次のとおりです:
整数配列 nums と整数 val を指定すると、nums in-place 内の val の出現箇所をすべて削除します。要素の順序は変更される場合があります。次に、val. に等しくない要素の
数を nums で返します。val に等しくない nums 内の要素の数が k であることを考慮します。受け入れられるには、次のことを行う必要があります。
カスタムジャッジ:
審査員は次のコードを使用してあなたのソリューションをテストします:
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すべてのアサーションが合格した場合、ソリューションは受け入れられます。
例 1:
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).例 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 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).これが私がそれを解決した方法です:
この問題を解決するために、私は 2 つの主な戦略を使用しました:
- インプレース置換: val に等しくない要素を格納する新しい配列を作成する代わりに、同じ配列番号を使用して、削除する必要がある要素を上書きします。
- 2 ポインター手法: 1 つのポインター (i) は配列内の各要素を反復処理し、別のポインター (k) は次の非 val 要素が配置される位置を追跡します。
class Solution: def removeElement(self, nums: List[int], val: int) -> int: k = 0
for i in range(len(nums)): if nums[i] != val: nums[k] = nums[i] k = 1
return k
完成したソリューションは次のとおりです:
class Solution: def removeElement(self, nums: List[int], val: int) -> int: k = 0 for i in range(len(nums)): if nums[i] != val: nums[k] = nums[i] k = 1 return k
免責事項: 提供されるすべてのリソースの一部はインターネットからのものです。お客様の著作権またはその他の権利および利益の侵害がある場合は、詳細な理由を説明し、著作権または権利および利益の証拠を提出して、電子メール [email protected] に送信してください。 できるだけ早く対応させていただきます。
Copyright© 2022 湘ICP备2022001581号-3