코딩테스트 준비/기타문제
[JAVA][Array] MoveZeros
AtoZ 개발자
2021. 1. 25. 22:00
반응형
1. 문제
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.
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.
2. 문제해설
숫자들이 주어졌을때 숫자간의 순서는 유지하되 0만 맨끝쪽으로 이동시키게 하라
3. 코드포맷
public class MoveZeros {
public static void main(String args[]) {
int[] nums = { 0, 3, 2, 0, 8, 5 };
}
}
4. 접근 방법
주어진 숫자 중 0이 아닌 숫자를 앞으로 당기고 나서 나머지 숫자를 0으로 채운다.
5. 코드
public class MoveZeros {
public static void main(String args[]) {
int[] nums = { 0, 3, 2, 0, 8, 5 };
//자바에서는 int 배열 선언시 default로 0으로 채워진다
int[] newNums = new int[nums.length];
int index=0;
for(int num:nums) {
if(num!=0) {
newNums[index++]=num;
}
}
print(newNums);
}
//출력함수
public static void print(int[] nums) {
for(int num:nums) {
System.out.print(num+" ");
}
System.out.println();
}
}
반응형