-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathZeroRightAlign.java
More file actions
51 lines (41 loc) · 1.29 KB
/
Copy pathZeroRightAlign.java
File metadata and controls
51 lines (41 loc) · 1.29 KB
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package Algorithms;
import java.util.ArrayList;
import java.util.Scanner;
/**
* 정수 배열(int array)이 주어지면 0이 아닌 정수 순서를 유지하며 모든 0을 배열 오른쪽 끝으로 옮기시오.
* 단, 시간복잡도는 O(n), 공간복잡도는 O(1)여야 합니다.
*
* ex)
* Input: [0, 5, 0, 3, -1]
* Output: [5, 3, -1, 0, 0]
*
* Input: [3, 0, 3]
* Output: [3, 3, 0]
*/
public class ZeroRightAlign {
public ArrayList<Integer> moveZero(ArrayList<Integer> list) {
ArrayList<Integer> result = new ArrayList<>();
int front = 0;
for(int num: list) {
if(num == 0) {
result.add(num);
} else {
result.add(front, num);
front ++;
}
}
return result;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String input = in.nextLine();
String[] inputAry = input.split(" ");
ArrayList<Integer> list = new ArrayList<>();
for(String num : inputAry) {
list.add(Integer.parseInt(num));
}
System.out.println("Input: " + list);
ZeroRightAlign zeroRightAlign = new ZeroRightAlign();
System.out.println("Output: " + zeroRightAlign.moveZero(list));
}
}