手機(jī)上如何做網(wǎng)站湖南靠譜seo優(yōu)化
題目
給你一個(gè)數(shù)組?
?和一個(gè)值?
,你需要?原地?移除所有數(shù)值等于?
?的元素,并返回移除后數(shù)組的新長(zhǎng)度。
不要使用額外的數(shù)組空間,你必須僅使用?
?額外空間并?原地?修改輸入數(shù)組。
元素的順序可以改變。你不需要考慮數(shù)組中超出新長(zhǎng)度后面的元素。
解題
def remove_element(nums, val):# 初始化新數(shù)組索引new_index = 0for current_index in range(len(nums)):if nums[current_index] != val:nums[new_index] = nums[current_index]new_index += 1return new_index# 測(cè)試?yán)?nums = [3, 2, 2, 3]
value = 3
new_length = remove_element(nums, value)
print("新數(shù)組的長(zhǎng)度:", new_length)
print("移除后的數(shù)組:", nums[:new_length])
新數(shù)組的長(zhǎng)度: 2
移除后的數(shù)組: [2, 2]