ⅩⅡ. sort by Height
Some people are standing in a row in a park. There are trees between them which cannot be moved. Your task is to rearrange the people by their heights in a non-descending order without moving the trees. People can be very tall!
// 값이 -1 인 원소는 그대로 두고 나머지 값들을 오름차순으로 정렬해라
Example
Fora = [-1, 150, 190, 170, -1, -1, 160, 180], the output should be
sortByHeight(a) = [-1, 150, 160, 170, -1, -1, 180, 190].
Input/Output
[execution time limit] 3 seconds (java)
[input] array.integer a
Ifa[i] = -1, then theithposition is occupied by a tree. Otherwisea[i]is the height of a person standing in theithposition.
Guaranteed constraints:
1 ≤ a.length ≤ 1000,
-1 ≤ a[i] ≤ 1000.
[output] array.integer
Sorted arrayawith all the trees untouched.
》》
int[] sortByHeight(int[] a) {
for(int i=0;i<a.length-1;i++){
for(int j=i+1;j<a.length;j++){
if(a[i]>-1 && a[j]>-1){ // a[i],a[j] 값이 -1 이상일 때 ( --> -1이면 무시 )
if(a[i]>a[j]){ // 오름차순 정렬
int temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
}
return a;
}
'코딩테스트' 카테고리의 다른 글
CodeSignal / Intro / Smooth Sailing (1/2) (0) | 2020.02.20 |
---|---|
CodeSignal / Intro / Edge of the Ocean _2 (0) | 2020.02.19 |
CodeSignal / Intro / Edge of the Ocean _1 (0) | 2020.02.19 |
CodeSignal / Intro / The Journey Begins (0) | 2020.02.19 |