본문 바로가기

728x90

알고리즘

(6)
[프로그래머스] 정렬 가장 큰 수 - 정렬의 기초를 연습하기에 좋은 문제 class Solution { public String solution(int[] numbers) { String[] strs = new String[numbers.length]; for (int i = 0; i (o2 + o1).compareTo(o1 + o2)); String answer = ""; for (String s : strs) { answer += s; } if (answer.charAt(0) == '0') return "0"; return answer; } } // 스트..
[프로그래머스] Greedy 그리디 알고리즘은, 탐욕적 알고리즘으로 불리며 순간에서 가장 최선의 선택을 하면 결과적으로 가장 효율적인 알고리즘이다. 기지국 설치 - 큐로 풀면 시간 초과 나옴 public int solution(int n, int[] stations, int w) { int answer = 0; int index = 0; int position = 1; while (position = need) break; int making = Math.min(limit, need - made); answer += making * price; made += making; if (monthlyOrder[j] == 0) continue; need -= monthlyOrder[j]; int delivery = Math.min(made,..
[프로그래머스] 최댓값 만들기 (1) import java.util.ArrayList; import java.util.Arrays; import java.util.stream.Collectors; class Solution { public int solution(int[] numbers) { int answer = 0; ArrayList arrayList = Arrays.stream(numbers).boxed().collect(Collectors.toCollection(ArrayList::new)); for (int i = 0; i < arrayList.size() - 1; i++) { for (int j = i + 1; j < arrayList.size(); j++) { int element = arrayList.get(i) * array..
[프로그래머스] 구슬을 나누는 경우의 수 문제를 보자마자 팩토리얼 재귀함수로 구하면 된다고 생각했었다. class Solution { public int solution(int balls, int share) { if (balls == share) return 1; return makeFactory(balls) / (makeFactory(balls - share) * makeFactory(share)); } public int makeFactory(int num) { if (num == 0) { return 1; } return num * makeFactory(num - 1); } } } - 그런데 이렇게 하니까 안되는 경우가 있었음 - 인터넷 찾아보니 int 범위를 넘는 케이스가 존재하기 때문에 어쩔 수가 없음 - 4바이트의 메모리가 할당되며..
[프로그래머스] 분수의 덧셈 최대 공약수랑 최소 공배수를 바로 생각했었어야 했는데 진짜 무식하게 풀었다. 두 분수를 더한 값을 분자는 0, 분모는 1 인덱스에 넣어주는 문제다. JavaScript - 최소 공배수로 깔끔하게 했으면 됐는데, 그냥 머리속에 계산 하듯이 조건 나눴다. - 정답이 안 나오길래 보니 마지막에 약분을 해야한다. function solution(numer1, denom1, numer2, denom2) { let answer = null; if (denom1 % denom2 == 0 || denom2 % denom1 == 0) { if (denom1 >= denom2) { const div = denom1 / denom2; answer = [numer1 + numer2 * div, denom1]; } else {..
[프로그래머스] 옹알이(1) 아기들이 특정 단어밖에 말할 수 없다는 점을 이용한 문제이다. 개인적으로 다른 사람 풀이 봤을 때, 이걸 정규식으로 푼 걸 보고 놀랬다... JavaScript - 함수를 일단 분리했고, 단어마다 check를 하도록 구성했다. - 일단 말할 수 있는 단어가 나오면 @로 replace를 한 후, 마지막에 @를 빈 문자열로 만들어 애기가 말할 수 있는 단어인지 최종 판단한다. function solution(babbling) { let count = 0; babbling.forEach((word) => { if (checkWord(word)) { count += 1; } }) return count; } // Return Boolean function checkWord(word) { const babyWor..

728x90