leetcode 27. Remove Element
移除给定的元素,可能移除多个,返回数组的长度
var removeElement = function(nums, val) { for(var i = nums.length-1; i>= 0; i--){ var el = nums[i] if(el === val){ nums.splice(i,1) } } return nums.length }
不使用splice
var removeElement = function (nums, val) { let n = nums.length, removeCount = 0, changeableLen = n; for (let i = 0; i < changeableLen; i++) { let el = nums[i]; if (el === val) { let j = i removeCount++ changeableLen = n - removeCount //全部前进一格 while (j < changeableLen) { nums[j] = nums[j + 1] j++ } i--;//可能nums[j-1]也等于val } } nums.length = changeableLen return changeableLen }
使用后面的数取替 目标元素
var arrayLength = nums.length; var i = 0; while(i < arrayLength) { if(nums[i] == val) { nums[i] = nums[arrayLength - 1];//找后面的元素代替它 //注意这时,i没有变化,可能新的 nums[i] == val //但arrayLength变化,我们又可能取倒数第二,第三的元素代替它 arrayLength--; } else { i++; } } return arrayLength; }
另一种两端移动删除的实现
let i = 0, j = nums.length - 1; for(;;) { while(i < j && nums[i] !== val){ i++; } while(i < j && nums[j] === val){ j--; } if (i === j) { if (nums[i] === val) { return i; }else{ return i+1; } } else if(i < j){ nums[i++] = nums[j--]; }else{ return i; } }
相关推荐
wikiwater 2020-10-27
IdeaElements 2020-08-19
Sophiego 2020-08-16
Kakoola 2020-08-01
Kakoola 2020-07-29
ELEMENTS爱乐冬雨 2020-07-18
ELEMENTS爱乐小超 2020-07-04
ELEMENTS爱乐小超 2020-07-04
Kakoola 2020-06-28
Feastaw 2020-06-18
Wmeng0 2020-06-14
ELEMENTS爱乐冬雨 2020-06-14
云之高水之远 2020-06-14
哈喽elements 2020-06-14
Feastaw 2020-06-11