Notice
Recent Posts
Recent Comments
Link
반응형
개발에 AtoZ까지
[JAVA][Array] MoveZeros 본문
반응형
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();
}
}
반응형
'코딩테스트 준비 > 기타문제' 카테고리의 다른 글
[JAVA][Array] LicenseKey Formatting (0) | 2021.01.27 |
---|---|
[JAVA][Array] Jewels And Stones (0) | 2021.01.27 |
[JAVA][Array] MeetingRoom2 (0) | 2021.01.26 |
[JAVA][Array] MergeInterval (0) | 2021.01.26 |
[JAVA][Array] Daily Temperature (0) | 2021.01.26 |
[JAVA][Array] TwoSum (0) | 2021.01.26 |
[JAVA][Array] MeetingRoom (0) | 2021.01.25 |
Comments