리그캣의 개발놀이터

매일프로그래밍 - Question 9 본문

알고리즘/매일프로그래밍

매일프로그래밍 - Question 9

리그캣 2018. 4. 17. 18:28

정수 배열(int array)이 주어지면 0이 아닌 정수 순서를 유지하며 모든 0을 배열 오른쪽 끝으로 옮기시오. 단, 시간복잡도는 O(n), 공간복잡도는 O(1)여야 합니다.




예제)


Input: [0, 5, 0, 3, -1]


Output: [5, 3, -1, 0, 0]




Input: [3, 0, 3]


 Output: [3, 3, 0]



#define _CRT_SECURE_NO_WARNINGS
#include <cstdio>
#include <iostream>
#define Length 3
using namespace std;
int main() {
int arr1[Length];
int arr2[Length];
for (int i = 0; i < Length; i++) {
scanf("%d", &arr1[i]);
}
int j = 0;
int k = Length-1;
for (int i = 0; i < Length; i++) {
if(arr1[i]!=0){
arr2[j] = arr1[i];
j++;
}
else{
arr2[k] = 0;
k--;
}
}
for (int i = 0; i < Length; i++) {
printf("%d ", arr2[i]);
}
printf("\n");
return 0;
}



Length를 변경하여 작성하면 된다.



Comments