27. Remove Element
創(chuàng)新互聯(lián)專業(yè)為企業(yè)提供南寧網(wǎng)站建設(shè)、南寧做網(wǎng)站、南寧網(wǎng)站設(shè)計、南寧網(wǎng)站制作等企業(yè)網(wǎng)站建設(shè)、網(wǎng)頁設(shè)計與制作、南寧企業(yè)網(wǎng)站模板建站服務(wù),十多年南寧做網(wǎng)站經(jīng)驗,不只是建網(wǎng)站,更提供有價值的思路和整體網(wǎng)絡(luò)服務(wù)。
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ù)給定一個數(shù)組和一個關(guān)鍵值,刪除數(shù)組所有與關(guān)鍵值一樣的元素,并返回新的數(shù)組長度。
解題:
逐一遍歷數(shù)組元素,逐個比較,進(jìn)行操作。
1)如果數(shù)組中元素值一致時,只需要將數(shù)組長度減一;否則,把cnt中下標(biāo)元素賦值給index的位置。因為如果中間出現(xiàn)給定值時,覆蓋掉該位置值。
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; }