문제를 이해하고 있다면 바로 풀이를 보면 됨
전체 코드로 바로 넘어가도 됨
마음대로 번역해서 오역이 있을 수 있음
주어진 막대 길이 배열에서 3개의 막대를 사용해서 최대 둘레를 가진 삼각형을 그려라. 3개의 정수로 오름차순 순서로 측면의 길이를 나타내는 배열을 반환해라.
최대 둘레를 가진 여러 유효한 삼각형이 있는 경우:
만약 삼각형이 존재하지 않다면, [-1]을 반환해라.
sticks = [1, 2, 3, 4, 5, 10]
세 개의 수가 (1, 2, 3)인 경우 삼각형을 형성되지 않는다. (4, 5, 10) 또는 (2, 3, 5)도 아니라서, 문제는 (2, 3, 4)와 (3, 4, 5)로 축소된다. 가장 긴 길이는 3 + 4 + 5 = 12 이다.
maximumPerimeterTriangle 함수를 완성해라.
maximumPerimeterTriangle 함수는 아래와 같은 매개변수를 가지고 있다.
삼각형의 조건인 두 변의 길이의 합이 나머지 한변의 길이보다 크다라는 것을 알고 있다면 쉽게 해결할 수 있다.
먼저 주어진 배열 sticks를 내림차순으로 정렬한다.
sticks.sort(Comparator.reverseOrder());
정수형 리스트 result를 생성한다. 결과값으로 반환할 리스트이다.
List<Integer> result = new ArrayList<>();
for문을 통해 삼각형이 되는지 찾아준다. 이때 isTriangled 메소드를 따로 만들어서 삼각형인지 아닌지 판별해준다.
public static boolean isTriangled(int a, int b, int c){
if(a + b <= c) return false;
if(a + c <= b) return false;
if(b + c <= a) return false;
return true;
}
for(int i = 0; i < sticks.size() - 2; i++){
if(isTriangled(sticks.get(i), sticks.get(i + 1), sticks.get(i + 2))){
result.add(sticks.get(i + 2));
result.add(sticks.get(i + 1));
result.add(sticks.get(i));
return result;
}
}
만약 조건에 걸리지 않고 반복문에서 빠져나온다면 result에 -1을 추가하고, result를 반환한다.
result.add(-1);
return result;
public static List<Integer> maximumPerimeterTriangle(List<Integer> sticks) {
sticks.sort(Comparator.reverseOrder());
List<Integer> result = new ArrayList<>();
for(int i = 0; i < sticks.size() - 2; i++){
if(isTriangled(sticks.get(i), sticks.get(i + 1), sticks.get(i + 2))){
result.add(sticks.get(i + 2));
result.add(sticks.get(i + 1));
result.add(sticks.get(i));
return result;
}
}
result.add(-1);
return result;
}
public static boolean isTriangled(int a, int b, int c){
if(a + b <= c) return false;
if(a + c <= b) return false;
if(b + c <= a) return false;
return true;
}