283. Move Zeroes

inhalin·2021년 2월 24일
0

Leetcode Easy

목록 보기
11/14

문제

Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements.

주어진 배열에서 0이 아닌 나머지 요소의 순서를 유지하면서 0을 전부 뒤로 보내라.

Example:

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

Note:

  • You must do this in-place without making a copy of the array.
  • Minimize the total number of operations.

Solution

  1. 먼저 i가 첫번째 요소, j가 두번째 요소를 가리키는 가상의 포인터 두개를 만들어준다.
  2. i번째 값이 0이 아니면 두 포인터를 한칸씩 옆으로 보낸다.
  3. i번째가 0이고 j번째가 0이 아니면 두개의 순서를 바꿔준다.
  4. 둘다 0이면 j번째만 한칸 옆으로 이동한다.
  5. j가 배열끝을 가리킬때까지 반복한다.
class Solution {
    public void moveZeroes(int[] nums) {
        int i = 0;
        int j = 1;
        
        while(j<nums.length){
            if(nums[i] != 0){
                i++;
                j++;
            } else if(nums[i] == 0 && nums[j] !=0){
                nums[i] = nums[j];
                nums[j] = 0;
                i++;
                j++;
            } else if(nums[i] == 0 && nums[j] ==0){
                j++;
            }
        }
    }
}

0개의 댓글