只移动0,其他顺序不变;必须在元素组进行操作
会改变原数组内的值类型
const moveZeroByReg = (arr = [1,0,2,0,3,0,4,0,5]) => { const reg = /0/g let str = arr.join('') const res = str.match(reg) str = str.replace(reg, '') str += res.join('') arr = str.split('') return arr }
使用splice 时间复杂度O(n^2)
const removeZeroBySplice = (arr = [1,0,2,0,3,0,4,0,5]) => { const { length } = arr let zeroCount = 0 for(let i = 0; i < length - zeroCount; i++ ){ if(arr[i] === 0){ arr.splice(i,1) arr.push(0) i-- zeroCount++ } } return arr }
双指针
const moveZeroByDoublePointer = (arr = [1,0,2,0,3,0,4,0,5]) => { const { length } = arr let firstZeroIndex = -1 for(let i = 0; i < length; i++){ const value = arr[i] if(value === 0){ if(firstZeroIndex < 0){ firstZeroIndex = i } }else { if(firstZeroIndex >= 0 ){ arr[i] = 0 arr[firstZeroIndex] = value firstZeroIndex++ } } } return arr }
标签:arr,const,数组,firstZeroIndex,++,let,str,移动,末尾 From: https://www.cnblogs.com/zhenjianyu/p/17068475.html