기타/코딩테스트

프로그래머스 코딩테스트 lv2-구명보트 : int 배열 정렬

DEV_HEO 2023. 2. 23. 16:31
320x100

https://school.programmers.co.kr/learn/courses/30/lessons/42885

 

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

int 배열 정렬하기

 

Arrays.sort 이용

 

오름차순 ->

int[] intArray = {1,3,5,7,2,4,6};

Arrays.sort(intArray);

내림차순 ->

int[] intArray = {1,3,5,7,2,4,6};

// primitive Type을 Wrapper클래스로 박싱해주어야 reverseOrder 사용가능.
Integer[] tmp = Arrays.stream(intArray).boxed().toArray(Integer[]::new);
Arrays.sort(tmp, Comparator.reverseOrder()); // 내림차순

풀이

class Solution {
    public int solution(int[] people, int limit) {
        int answer = 0;
		
	    Arrays.sort(people);
		
		int bottom = 0;
		int top = people.length-1;
		
		while(true) {
			
			if(people[bottom] + people[top] <= limit) {
				bottom++;
			}
			
			top--;
			answer++;
			
			if(bottom > top) break;
			
		}
		
		return answer;
    }
}

힌트를 많이 찾아보고 겨우 풀었다.

이 문제도 코드에 비해 너무 오래 풀었다.

 

오래걸린 이유

1. 구명보트에 최대 2명만 태울 수 있는데, 이걸 못보고 몸무게 제한까지 몇명이든 태울 수 있는 줄 알고 엄청 돌아갔다.

덕분에 반복문도 두개 쓰고,,정답률을 100이었지만 효율성 0이었다.

 

2. 반복문 안의 코드를 좀더 간결하게 줄이지 못했다.

while(true){
	if(bottom == top) {
        answer++;
        break;
    }


    if(list.get(bottom) + list.get(top) <= limit) {
        top--;
    }

    bottom++;
    answer++;

    if(bottom > top) break;
    if(bottom == list.size()) break;
}

결과는 같지만 많이 돌아가는 느낌...

 

다음엔 문제를 좀 더 꼼꼼히 읽어보자

320x100

'기타 > 코딩테스트' 카테고리의 다른 글

프로그래머스 코딩테스트 lv2-다음 큰 숫자  (0) 2023.02.02