본문 바로가기
Research/problems

LeetCode_283_Move Zeros

by RIEM 2022. 11. 24.

date: 2022-11-24level: easy

Problem

My Solution

/**
 * @param {number[]} nums
 * @return {void} Do not return anything, modify nums in-place instead.
 */
var moveZeroes = function(nums) {

	let count = 0;
	let chance = nums.length
	while (chance) {
		if(nums[0] === 0) {
			nums.shift();
			count++
		} else {
			nums[nums.length] = nums[0]
			nums.shift();
		}
		chance--
	}
    
	while(count) {
		nums.push(0);
		count--
	}
		
	return nums
};

 

Runtime: 168 ms, faster than 34.41% of JavaScript online submissions for Move Zeroes.

Memory Usage: 47.4 MB, less than 7.78% of JavaScript online submissions for Move Zeroes.

 

Other Good Solution

내가 chance 변수를 주고 기회를 날리는 방식을 이 사람은 for in의 i값에 nums.length - 1 를 추고 회전 시 i--하는 방식으로 적용했다. 

그런데 이 사람은 역으로 0을 제거하는 방법을 썼는데, push와 자연스럽게 맞물리는 방식이라고 생각한다. 반복문으로 처리할 때 항상 좌에서 우로 할 필요 없이 뒤에서 앞으로 적용을 하는 방법도 생각해보면 좋다고 생각했다.

https://leetcode.com/problems/maximum-subarray/discuss/791430/Javascript-Solution%3A53-(speedgreater95)

 
/**
* @param {number[]} nums
* @return {void} Do not return anything, modify nums in-place instead.
*/
let moveZeroes = function(nums) {
        for(let i= nums.length-1; i>=0; i--){
            if(nums[i]===0){
                nums.push(0)
                nums.splice(i,1)
            }
        }
        return nums
    };

Runtime: 80 ms, faster than 80.00% of JavaScript online submissions for Move Zeroes.

Memory Usage: 38.6 MB, less than 24.75% of JavaScript online submissions for Move Zeroes.

Feedback Appreciated

 

 

 

댓글