-
프로그래머스 - 체육복알고리즘 2022. 8. 19.반응형
내 풀이
import java.util.Arrays; public class P_42 { public static int solution(int n, int[] lost, int[] reserve) { int answer = n-lost.length; Arrays.sort(lost); Arrays.sort(reserve); // 두 배열의 중복 값 처리 for(int i=0; i<lost.length; i++) { for(int x=0; x<reserve.length; x++) { if(lost[i] == reserve[x]) { lost[i] = -1; reserve[x] = -1; answer++; break; } } } // 체육복 빌려주는 로직 for(int i=0; i<lost.length; i++) { for(int j=0; j<reserve.length; j++) { if(reserve[j] == lost[i]-1) { answer++; reserve[j] = -1; lost[i] = -1; break; } else if(reserve[j] == lost[i]+1) { answer++; reserve[j] = -1; lost[i] = -1; break; } } } return answer; } public static void main(String[] args) { // 체육복 int n = 3; // 전체 학생 수 int[] lost = {1,2}; // 체육복 잃어버린 학생 번호 int[] reserve = {2,3}; // 여분의 체육복을 가지고 있는 학생 번호 System.out.println(solution(n, lost, reserve)); } }
주의해야 할 점 2가지
1. lost의 배열과 reserve의 배열의 원소가 겹칠 경우 = 여분의 체육복을 가지고 있는데 본인 체육복을 잃어버린 학생의 경우의 수
2. 오름차순 정렬
두 배열의 중복 값 처리를 위해서 그냥 중복인 해당 원소를 -1로 바꿔치기 함.
어차피 lost 배열과 reserve 배열의 원소 최소 값 조건은 1이상이기 때문에 계산에 포함 되지 않을 수를 넣어주면 된다.
다른 사람 풀이
class Solution { public int solution(int n, int[] lost, int[] reserve) { int[] people = new int[n]; int answer = n; for (int l : lost) people[l-1]--; for (int r : reserve) people[r-1]++; for (int i = 0; i < people.length; i++) { if(people[i] == -1) { if(i-1>=0 && people[i-1] == 1) { people[i]++; people[i-1]--; }else if(i+1< people.length && people[i+1] == 1) { people[i]++; people[i+1]--; }else answer--; } } return answer; } }
반응형'알고리즘' 카테고리의 다른 글
프로그래머스 - 콜라 문제 (0) 2022.11.04 프로그래머스 - 삼총사 (0) 2022.10.15 프로그래머스 - 실패율 (0) 2022.08.04 프로그래머스 - 약수의 개수와 덧셈 (0) 2022.07.24 프로그래머스 - 3진법 뒤집기 (0) 2022.07.22