본문 바로가기

알고리즘

프로그래머스42885 - 이중 for문 성능 올리기

728x90

size(), length(), length등 길이를 계산하는 함수를 최소화한다. (특히 종료조건에서)

반복문 안에서 배열 사용을 최소화 -> 임시 변수를 사용하자

break, continue문을 활용하자

정말 이중 for문이 필요할까? 다시 생각해보자

 

 

효율성 테스트에서 막혀서 계속 고쳐보았다.

원래 코드

import java.util.*;

class Solution {
    public int solution(int[] people, int limit) {
        int count = people.length;
        Arrays.sort(people);
        
        int tempI;
        
        for(int i=count-1; i>0; i--){
            tempI = people[i];
            for(int j=i-1; j>=0 ; j--){
                if(tempI + people[j]<= limit){
                    people[j]=limit+1;
                    count--;
                    break;
                }
            }
            people[i]=limit+1;
        }
        
        return count;
    }
}

 

최종 코드

import java.util.Arrays;

class Solution {
    public int solution(int[] people, int limit) {
        int length = people.length;
        int count = 0; 
        
        // 오름차순 정렬
        Arrays.sort(people);
        
        // 가장 무거운 사람부터 실행
        for(int i=length-1; i>0; i--){ 
            
            // 같이 태울 사람이 없다면
            if(count >= i) break; 
            
            // 현재 사람 몸무게 + 남아있는 사람 중 가장 적은 몸무게
            if(people[i] + people[count]<= limit){ 
                count++;
            }
        }
        
        // 전체 인원의 수 - 2명이 보트를 타는 경우
        return length-count; 
    }
}

 

고치다보니 이중 for문을 돌 필요가 전혀 없었다는 이야기였습니다.

'알고리즘' 카테고리의 다른 글

배열 내림차순 정렬  (0) 2021.02.23
백준 11399 String[] -> Int[]  (0) 2021.02.18
백준 16435 BufferedReader와 Scanner  (0) 2021.02.17
탐욕(그리디) 알고리즘  (0) 2021.02.16
1로 만들기  (0) 2021.02.06