Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
221 views
in Technique[技术] by (71.8m points)

javascript - Why my Move Zeroes function is wrong answer in leetcode?

I was doing Move Zeroes in leetcode.

I write a function to solve but leetcode said it's a wrong answer.

Could someone see what is wrong in my code?

Requirement:the original array must be mutated

Input:[0,1,0,3,12]

Output:[1,3,12,0,0]

Input:[2,1]

Output:[1,2]

enter image description here

Here is my JS:

var moveZeroes = function(nums) {
    var ZeroArray=[]
    for(let i=0;i<nums.length;i++){
        if(nums[i]===0){
            ZeroArray.push(nums[i])
            nums.splice(i,1);
        }
    }
    nums.sort((a,b)=>(a-b))
    for(let j=0;j<ZeroArray.length;j++){
        nums.push(ZeroArray[j])    
    }
    return nums;
};
console.log(moveZeroes([0,1,0,3,12])); //Should return [ 1,3,12,0,0]
console.log(moveZeroes([2,1]));//Should return [1,2]
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your

nums.shift(nums[i]);

will remove (and discard) whatever exists at the 0th index in nums at the time. It would probably be easier to push to a different array if the num is not 0, then combine the arrays at the end (no sorting):

var moveZeroes = function(nums) {
  var ZeroArray = []
  var nonZeroArray = [];
  for (let i = 0; i < nums.length; i++) {
    if (nums[i] === 0) {
      ZeroArray.push(nums[i])
    } else {
      nonZeroArray.push(nums[i]);
    }
  }
  return [...nonZeroArray, ...ZeroArray];
};
console.log(moveZeroes([0, 1, 0, 3, 12])) //Should return [ 1,3,12,0,0]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...