서하아빠의 개발 블로그

283. Move Zeroes 본문

알고리즘/LeetCode

283. Move Zeroes

서하아빠 2021. 4. 7. 11:16

Given an integer arraynums, move all0's to the end of it while maintaining the relative order of the non-zero elements.

Notethat you must do this in-place without making a copy of the array.

Example 1:

Input: nums = [0,1,0,3,12] Output: [1,3,12,0,0]

Example 2:

Input: nums = [0] Output: [0]

Constraints:

  • 1 <= nums.length <= 104
  • -231<= nums[i] <= 231- 1

 

풀이방법

- swap을 이용한 방법으로 풀이

 

class Solution {
    public void moveZeroes(int[] nums) {
        int j = 0;
        for( int i=0; i < nums.length; i++ ) {
            if( nums[i] != 0 ) {
                // if i position is not 0, swap i and j number.
                swap( nums, i, j);
                j++;
            }
        }
    }
    
    private static void swap( int nums[], int i, int j) {
        int temp = nums[j];
        nums[j] = nums[i];
        nums[i] = temp;
    }
}

'알고리즘 > LeetCode' 카테고리의 다른 글

217. Contains Duplicate  (0) 2022.05.20
25. Reverse Nodes in k-Group  (0) 2022.05.20
61. Rotate List  (0) 2022.05.19
200. Number of Islands  (0) 2021.06.14
693. Binary Number with Alternating Bits  (0) 2021.04.20