Notice
Recent Posts
Recent Comments
Link
반응형
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
Tags
- 삼성
- 인프런
- array
- 자바
- SWEA
- 코테
- NestJS
- 삼성소프트웨어아카데미
- 코딩
- 배열
- AtoZ0403
- 자료구조
- 스텍
- 콜백지옥
- spring
- 자바스크립트
- java
- 중간 평균값 구하기
- 프로그래머스
- js
- 정렬
- 백준
- javascript
- 코딩테스트
- 카카오
- 알고리즘
- 코테준비
- mybatis
- 그리디알고리즘
- stack
Archives
- Today
- Total
개발에 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