您好,登錄后才能下訂單哦!
27. Remove Element
Given an array and a value, remove all instances of that value in place and return the new length.
Do not allocate extra space for another array, you must do this in place with constant memory.
The order of elements can be changed. It doesn't matter what you leave beyond the new length.
Example:
Given input array nums = [3,2,2,3]
, val = 3
Your function should return length = 2, with the first two elements of nums being 2.
題意:
根據(jù)給定一個(gè)數(shù)組和一個(gè)關(guān)鍵值,刪除數(shù)組所有與關(guān)鍵值一樣的元素,并返回新的數(shù)組長(zhǎng)度。
解題:
逐一遍歷數(shù)組元素,逐個(gè)比較,進(jìn)行操作。
1)如果數(shù)組中元素值一致時(shí),只需要將數(shù)組長(zhǎng)度減一;否則,把cnt中下標(biāo)元素賦值給index的位置。因?yàn)槿绻虚g出現(xiàn)給定值時(shí),覆蓋掉該位置值。
int removeElement(int* nums, int numsSize, int val) { int cnt = 0; int size = numsSize; int index = 0; for ( cnt = 0; cnt < numsSize; cnt++ ) { if ( *(nums + cnt) != val ) { *(nums + index) = *(nums + cnt); index++; } else { size -= 1; } } if ( index != numsSize ) { *(nums + index) = '\0'; } return size; }
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。