Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...