처음 풀이
import java.util.Arrays;
class Solution {
public int solution(int[] people, int limit) {
Arrays.sort(people);
//짝의 수
int count = 0;
//최대한 무게 차이가 많이 나는 사람끼리 짝해야 최소값
int index = people.length;
//짝 지어진 (무거운)사람의 index
//다음 cycle 때 index-1부터 탐색
for(int n=0; n<index; n++) {
for(int i=index-1; i>n; i--) {
if((people[n]+people[i])<=limit) {
index = i;
count++;
break;
}//if end
}//for end
//가장 가벼운 사람과 짝없는 경우 break;
if(index==people.length) break;
}//for end
return people.length-count;
}
}
다른 풀이
for문을 간략하게 만든 풀이
public int solution(int[] people, int limit) {
Arrays.sort(people);
int i = 0, j = people.length - 1;
for (; i < j; --j) {
if (people[i] + people[j] <= limit)
++i;
}
return people.length - i;
}
이중for문을 for문으로!
"--j"
'자료구조 & 알고리즘 > 문제풀이' 카테고리의 다른 글
모음 사전 - 프로그래머스 (Java, Level 2) (0) | 2022.02.25 |
---|---|
최댓값과 최솟값 - 프로그래머스 (Java, Level 2) (0) | 2022.02.21 |
큰 수 만들기 - 프로그래머스 (Java, Level 2) (0) | 2022.02.18 |
체육복 - 프로그래머스 (Java, Level 2) (0) | 2022.02.18 |
카펫 - 프로그래머스 (Java, Level 2) (0) | 2022.02.10 |
댓글