JAVAIARY

프로그래머스) 구명보트 본문

examplePractice

프로그래머스) 구명보트

shiherlis 2023. 2. 26. 16:22

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

 

프로그래머스

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

programmers.co.kr

 public int solution(int[] people, int limit) {
       int answer = 0; // 사용된 구명보트의 수
		Arrays.sort(people);
		// people 배열을 ArrayList 형식으로 변환
		ArrayList<Integer> peopleAl = new ArrayList<>();
		for (int person : people) {
			peopleAl.add(person);
		}
		// 남은 사람이 2명 이하 일 때까지 반복
		while (peopleAl.size() > 1) {
			int i = peopleAl.size() - 1;
			// 무조건 혼자 타야하는 경우
			if (peopleAl.get(i) > limit - 40) {
				peopleAl.remove(i);
				answer++;
			}
			// 몸무게를 더해서 limit이하인 승객(2명 탑승 가능)이 있으면 2명 내보냄
			else if (limit - peopleAl.get(0) >= peopleAl.get(i)) {
				peopleAl.remove(i);
				peopleAl.remove(0);
				answer++;
			}
			// 더해서 limit 이하인 승객이 없으면 승객1명만 태워서 내보냄
			else {
				peopleAl.remove(i);
				answer++;
			}
		}
		// 남은사람이 0명이면 skip, 1명이면 구명보트 1개 추가
		answer = peopleAl.size() == 1 ? answer += 1 : answer;


		return answer;
	}
  • 배열 정렬 
    Arrays.sort(array)
    항상 쓰면서도 항상 까먹는...함수 ...ㅎ
  • for문 쓸 때 런타임 에러 주의할 것