티스토리 뷰
목차
1. 잘라서 배열로 저장하기
👉 소스코드
public int[] solution(String s) {
int[] answer = new int[s.length()];
answer[0] = -1;
for (int i = 0; i < s.length(); i++) {
int tmp = s.lastIndexOf(s.substring(i, i + 1), i - 1);
if (tmp != -1) {
answer[i] = i - tmp;
} else {
answer[i] = tmp;
}
}
return answer;
}
- 풀지 못한 문제,,
2. 명예의 전당
👉 소스코드
public int[] solution(int k, int[] score) {
int[] answer = new int[score.length];
List<Integer> temp = new ArrayList<>();
for (int i = 0; i < score.length; i++) {
if (temp.size() < k) {
temp.add(score[i]);
Collections.sort(temp);
answer[i] = temp.get(0);
continue;
}
if (temp.size() == k) {
int x = temp.get(0);
if (x < score[i]) {
temp.remove(0);
temp.add(score[i]);
Collections.sort(temp);
}
answer[i] = temp.get(0);
}
}
return answer;
}
- 명예의 전당으로 활용할 리스트를 만들어서 오름차순 정렬하고 앞에꺼 빼내는 방식을 반복하는 방법
3. 기사단원의 무기
👉 소스코드
public int solution(int number, int limit, int power) {
int answer = 0;
int cnt;
// 약수 구하기//
for (int i = 1; i <= number; i++) {
cnt = 0;
for (int j = 1; j <= Math.sqrt(i + 1); j++) {
if (i % j == 0) {
if (j * j == i) {
cnt += 1;
} else {
cnt += 2;
}
}
}
if (cnt > limit) {
answer += power;
} else {
answer += cnt;
}
}
return answer;
}
- 처음에 1부터 number까지 반복하면서 약수를 구했더니 시간초과가 났다.
제곱근 함수를 활용하여 수를 쪼개서 약수를 구하는 방법으로 반복문을 덜 돌렸더니 해결했다.
언제쯤 이러한 경우에수도 문제를 읽고 로직을 생각할 때 날것인지,,
4. 과일 장수
👉 소스코드
public int solution(int k, int m, int[] score) {
PriorityQueue<Integer> temp = new PriorityQueue<>(Collections.reverseOrder());
PriorityQueue<Integer> res = new PriorityQueue<>();
int answer = 0;
for(int x : score) {
temp.add(x);
}
while(true) {
if(temp.size() / m < 1 && res.size() == 0) {
break;
}
if(res.size() != m) {
res.add(temp.poll());
}else {
answer += (res.poll() * m);
res.clear();
}
}
return answer;
}
- 배열을 정렬한 다음 거꾸로 순회하면서 m만큼 인덱스를 가리켜 셈하면 쉬운문제
저는 참 어렵게도 풀죠? ^^;
5. 푸드 파이트 대회
👉 소스코드
public String solution(int[] food) {
List<String> reverseS = new ArrayList<>();
String leftAnswer = "";
String rightAnswer = "";
for(int i = 1; i < food.length; i++) {
if(food[i] != 1) {
String tmp = Integer.toString(i);
for(int j = 1; j <= food[i] / 2; j++) {
leftAnswer += tmp;
reverseS.add(tmp);
}
}
}
reverseS.sort(Comparator.reverseOrder());
reverseS.add(0, "0");
rightAnswer = String.join("", reverseS);
return leftAnswer + rightAnswer;
}
- 인덱스 1번 값부터 2로 나눈 몫을 인덱스 자리수만큼 두개의 문자열에 넣고 마지막에 문자열 하나를 뒤집는다
뒤집어진 문자열 맨 앞에 중앙에 위치해질 물을 넣고 문자열 두개를 합치면 끝!!
6. 햄버거 만들기
👉 소스코드
public int solution(int[] ingredient) {
int answer = 0;
ArrayList<Integer> arr = new ArrayList<Integer>();
for (int i = 0; i < ingredient.length; i++) {
arr.add(ingredient[i]);
if (3 < arr.size()) {
for (int j = arr.size() - 4; j < arr.size() - 3; j++) {
String s = "";
s = Integer.toString(arr.get(j))
+ Integer.toString(arr.get(j + 1))
+ Integer.toString(arr.get(j + 2))
+ Integer.toString(arr.get(j + 3));
if (s.equals("1231")) {
arr.remove(arr.size() - 1);
arr.remove(arr.size() - 1);
arr.remove(arr.size() - 1);
arr.remove(arr.size() - 1);
answer++;
}
}
}
}
return answer;
}
- ingredient 배열을 문자열로 만들고 1231이 있다면 ""로 replaceFirst 했더니 시간초과가 나서 로직을 리팩토링 했다. 분명 배열로 풀이가 가능한 문제로 보여졌는데 로직이 떠오르지 않아 Array를 사용했다.
7. 옹알이(2)
👉 소스코드
public int solution(String[] babbling) {
int answer = 0, length = 0;
String aya = "aya", ye = "ye", woo = "woo", ma = "ma";
for (int i = 0; i < babbling.length; i++) {
babbling[i] = babbling[i].replace(aya, "1");
babbling[i] = babbling[i].replace(ye, "2");
babbling[i] = babbling[i].replace(woo, "3");
babbling[i] = babbling[i].replace(ma, "4");
if (babbling[i].indexOf("11") == -1) {
if (babbling[i].indexOf("22") == -1) {
if (babbling[i].indexOf("33") == -1) {
if (babbling[i].indexOf("44") == -1) {
if (babbling[i].contains("1")
|| babbling[i].contains("2")
|| babbling[i].contains("3")
|| babbling[i].contains("4")) {
length = babbling[i].length()
- babbling[i].replaceAll("[^0-9]", "")
.length();
if (length == 0) {
answer++;
}
}
}
}
}
}
}
return answer;
}
7. 콜라문제
👉 소스코드
public int solution(int a, int b, int n) {
int answer = 0;
while (n > a) {
answer += (n / a) * b;
n = ((n / a) * b) + (n % a);
}
return answer;
}
8. 삼총사
👉 소스코드
public int solution(int[] number) {
int answer = 0;
for (int i = 0; i < number.length; i++) {
for (int j = i + 1; j < number.length; j++) {
for (int k = j + 1; k < number.length; k++) {
if (number[i] + number[j] + number[k] == 0) {
answer++;
}
}
}
}
return answer;
}
9. 숫자 짝꿍
👉 소스코드
public String solution(String X, String Y) {
StringBuffer res = new StringBuffer("");
char[] xArray = X.toCharArray();
char[] yArray = Y.toCharArray();
Arrays.sort(xArray);
Arrays.sort(yArray);
int xIndex = 0, yIndex = 0;
while(xIndex < xArray.length && yIndex < yArray.length) {
if(xArray[xIndex] == yArray[yIndex]) {
res.append(String.valueOf(xArray[xIndex]));
xIndex++;
yIndex++;
}else if(xArray[xIndex] < yArray[yIndex]) {
xIndex++;
}else{
yIndex++;
}
}
if(res.length() < 1) return "-1";
res.reverse();
String answer = res.toString();
if(answer.charAt(0) == '0') return "0";
return answer;
}
- 풀지 못해 다른 사람의 코드를 참고해가면서 문제를 풀고 이해하였다,
반복문을 돌려가면서 배열을 만들어 풀이하는 사람들이 대부분이었으나 나는 이 방법이 더 이해하기 쉬어 해당 코드를 풀이하는데 참고하기로 했다. X, Y를 배열로 만들고 오름차순 정렬을 한뒤에 숫자가 같은지를 체크해가면서 문자열에 누적해가면서 푸는 방법이였다.
준비하고 있는 코테가 당장 이번주 주말인데,, OTL
10. 성격 유형 검사하기 (2022 KAKAO TECH INTERNSHIP)
👉 소스코드
public String solution(String[] survey, int[] choices) {
HashMap<Character, Integer> scoreMap = new HashMap<>();
scoreMap.put('R', 0); scoreMap.put('T', 0);
scoreMap.put('C', 0); scoreMap.put('F', 0);
scoreMap.put('J', 0); scoreMap.put('M', 0);
scoreMap.put('A', 0); scoreMap.put('N', 0);
int[] surveyNumbmer = { 3, 2, 1, 0, 1, 2, 3 };
String answer = "";
for (int i = 0; i < choices.length; i++) {
int tmpScore = surveyNumbmer[choices[i] - 1];
if (choices[i] < 4) {
scoreMap.put(survey[i].charAt(0), scoreMap.get(survey[i].charAt(0)) + tmpScore);
}else {
scoreMap.put(survey[i].charAt(1), scoreMap.get(survey[i].charAt(1)) + tmpScore);
}
}
if (scoreMap.get('R') >= scoreMap.get('T')) {
answer += 'R';
}
if (scoreMap.get('R') < scoreMap.get('T')) {
answer += 'T';
}
if (scoreMap.get('C') >= scoreMap.get('F')) {
answer += 'C';
}
if (scoreMap.get('C') < scoreMap.get('F')) {
answer += 'F';
}
if (scoreMap.get('J') >= scoreMap.get('M')) {
answer += 'J';
}
if (scoreMap.get('J') < scoreMap.get('M')) {
answer += 'M';
}
if (scoreMap.get('A') >= scoreMap.get('N')) {
answer += 'A';
}
if (scoreMap.get('A') < scoreMap.get('N')) {
answer += 'N';
}
return answer;
}
- 처음에 Map을 쓸까 하다가 삽질 하고 Hash를 써서 해결했다. 비록 인턴쉽에 나온 문제였지만 그래도 1승!
11. 나머지가 1이 되는 수 찾기
👉 소스코드
public int solution(int n) {
int answer = 0;
for (int i = 2; i <= n; i++) {
if (n % i == 1) {
answer = i;
break;
}
}
return answer;
}
12. 최소직사각형
👉 소스코드
public int solution(int[][] sizes) {
List<Integer> w = new ArrayList<Integer>();
List<Integer> h = new ArrayList<Integer>();
int tempW = 0;
int tempH = 0;
for(int i = 0; i < sizes.length; i ++) {
if(sizes[i][0] < sizes[i][1]) {
tempW = sizes[i][1];
tempH = sizes[i][0];
}else {
tempW = sizes[i][0];
tempH = sizes[i][1];
}
h.add(tempH);
w.add(tempW);
}
w.sort(Comparator.reverseOrder());
h.sort(Comparator.reverseOrder());
return w.get(0) * h.get(0);
}
- 모든 명함을 돌려가면서 대보면 되는 문제
13. 없는 숫자 더하기
👉 소스코드
public int solution(int[] numbers) {
int answer = 45;
for (int i = 0; i < numbers.length; i++) {
answer -= numbers[i];
}
return answer;
}
14. 부족한 금액 계산하기
👉 소스코드
public long solution(int price, int money, int count) {
long answer = 0;
for (int i = 1; i < count + 1; i++) {
answer += (price * i);
}
if (answer == money || answer < money) {
answer = 0;
} else {
answer -= money;
}
return answer;
}
15. 숫자 문자열과 영단어(2021 카카오 채용 연계형 인턴쉽)
👉 소스코드
public int solution(String s) {
int answer = 0;
String tmp = s.replaceAll("[^0-9]", "");
if(s.length() == tmp.length()) {
answer = Integer.parseInt(s);
}else{
if(s.contains("zero")) s = s.replaceAll("zero", "0");
if(s.contains("one")) s = s.replaceAll("one", "1");
if(s.contains("two")) s = s.replaceAll("two", "2");
if(s.contains("three")) s = s.replaceAll("three", "3");
if(s.contains("four")) s = s.replaceAll("four", "4");
if(s.contains("five")) s = s.replaceAll("five", "5");
if(s.contains("six")) s = s.replaceAll("six", "6");
if(s.contains("seven")) s = s.replaceAll("seven", "7");
if(s.contains("eight")) s = s.replaceAll("eight", "8");
if(s.contains("nine")) s= s.replaceAll("nine", "9");
answer = Integer.parseInt(s);
}
return answer;
}
16. 약수의 개수와 덧셈
👉 소스코드
public int solution(int left, int right) {
int answer = 0;
int count = 0;
for(int i = left; i <= right; i++) {
for(int j = 1; j <= i; j++) {
if(i % j == 0) {
count++;
}
}
if(count % 2 == 0) answer += i;
if(count % 2 == 1) answer -= i;
count = 0;
}
return answer;
}
17. 음양 더하기
👉 소스코드
public int solution(int[] absolutes, boolean[] signs) {
int answer = 0;
for(int i = 0; i < signs.length; i++) {
if(signs[i] == true) {
answer += absolutes[i];
}else{
answer -= absolutes[i];
}
}
return answer;
}
18. 3진법 뒤집기
👉 소스코드
public int solution(int n) {
StringBuffer sb = new StringBuffer("");
String s = Integer.toString(n , 3);
sb.append(s);
sb.reverse();
String x = sb.toString();
int answer = Integer.parseInt(x, 3);
return answer;
}
- StringBuffer의 뒤집기를 이용하여 간편하게 풀이했다.
19. 두 개 뽑아서 더하기
👉 소스코드
public int[] solution(int[] numbers) {
HashSet<Integer> set = new HashSet<Integer>();
for(int i = 0; i < numbers.length; i++) {
for(int j = i + 1; j < numbers.length; j++) {
set.add(numbers[i] + numbers[j]);
}
}
Iterator<Integer> iterSet = set.iterator();
int[] answer = new int[set.size()];
int count = 0;
while(iterSet.hasNext()) {
answer[count] = iterSet.next();
count++;
}
for(int i = 0; i < answer.length; i++) {
for(int j = i; j < answer.length; j++) {
if(answer[i] > answer[j]) {
int tmp = answer[i];
answer[i] = answer[j];
answer[j] = tmp;
}
}
}
return answer;
}
20. 크레인 인형뽑기 (2019 카카오 개발자 겨울 인턴십)
👉 소스코드
public int solution(int[][] board, int[] moves) {
ArrayList<Integer> tmp = new ArrayList<Integer>();
tmp.add(0);
int answer = 0;
for (int i = 0; i < moves.length; i++) {
int count = 0;
for (int j = 0; j < board.length; j++) {
if (board[j][moves[i] - 1] != 0) {
if (tmp.get(tmp.size() - 1) == board[j][moves[i] - 1]) {
tmp.remove(tmp.size() - 1);
board[j][moves[i] - 1] = 0;
answer++;
count = 0;
break;
} else {
tmp.add(board[j][moves[i] - 1]);
board[j][moves[i] - 1] = 0;
count = 0;
break;
}
}
count++;
if (count == board.length) {
count = 0;
break;
}
}
}
return answer * 2;
}
- 0이 나올때 까지 순회하면서 0이 아닌수의 moves의 i - 1 의 자리가 나오면 바구니에 담고 바구니에 담을 때 바구니에 담겨 있는 수 중 담으려는 수와 같다면 카운팅을 해주는 식으로 풀이를 했다.
21. K번째 수
👉 소스코드
public int[] solution(int[] array, int[][] commands) {
int[] answer = new int[commands.length];
for (int i = 0; i < commands.length; i++) {
ArrayList<Integer> tmp = new ArrayList<Integer>();
for (int j = 0; j < array.length; j++) {
if (j >= commands[i][0] - 1 && j < commands[i][1]) {
tmp.add(array[j]);
}
}
Collections.sort(tmp);
answer[i] = tmp.get(commands[i][2] - 1);
}
return answer;
}
- 처음에 sublist로 잘라서가면서 풀었다가 sublist가 잘라서 가져온 mainlist와 연결되어 있다는 사실을 모르고 사용하다가 낭패를 봤었다.. 잘모르고 문제풀이를 한덕에 간단한 문제에서 삽질을 했다
22. 소수만들기
👉 소스코드
public int solution(int[] nums) {
int answer = 0;
int count = 0;
ArrayList<Integer> list = new ArrayList<Integer>();
for(int i = 0; i < nums.length; i++) {
for(int j = i + 1; j < nums.length; j++) {
for(int k = j + 1; k < nums.length; k++) {
list.add(nums[i] + nums[j] + nums[k]);
}
}
}
Collections.sort(list);
for(int i : list) {
for(int j = 2; j*j <= i; j++) {
if(i % j == 0) {
count++;
}
}
if(count == 0) {
answer++;
}
count = 0;
}
return answer;
}
23. 크기가 작은 부분 문자열
👉 소스코드
public int solution(String t, String p) {
int answer = 0;
int index = 0;
Long pNum = Long.parseLong(p);
while(index + p.length() <= t.length()) {
Long lengthNum = Long.parseLong(t.substring(index, index + p.length()));
System.out.println(lengthNum);
if(pNum >= lengthNum) answer++;
index++;
}
return answer;
}
}
- 주어진 문자열 t를 문자열 p의 길이만큼 잘라가면서 비교하였고 잘라야 하는 시작점을 index, 잘라야하는 끝부분은 index + p.length()로 표현하였습니다.
Level 2도 잘풀고 싶다
24. 개인정보 수집 유효기간(KAKAO BLIND RECRUITMENT)
👉 소스코드
public int[] solution(String today, String[] terms, String[] privacies) {
ArrayList<Integer> list = new ArrayList<Integer>();
LocalDate localToday = LocalDate.parse(today.replaceAll("\\.", "-"));
for(int i = 0; i < privacies.length; i++) {
char type = privacies[i].charAt(11);
LocalDate localTmp = LocalDate.parse(privacies[i].replaceAll("\\.", "-").substring(0, 10));
for(int j = 0; j < terms.length; j++) {
if(type == terms[j].charAt(0)) {
if(localToday.isEqual(localTmp.plusMonths(Integer.parseInt(terms[j].substring(2))))
|| localToday.isAfter(localTmp.plusMonths(Integer.parseInt(terms[j].substring(2))))) {
list.add(i+1);
}
}
}
}
int[] answer = new int[list.size()];
for(int i = 0; i < answer.length; i++) {
answer[i] = list.get(i);
}
return answer;
}
25. 신고 결과 받기
👉 소스코드
public int[] solution(String[] id_list, String[] report, int k) {
int[] answer = new int[id_list.length];
HashMap<String, HashSet<String>> map = new HashMap<String, HashSet<String>>();
HashMap<String, Integer> indexMap = new HashMap<String, Integer>();
for(int i = 0; i < id_list.length; i++) {
map.put(id_list[i], new HashSet<>());
indexMap.put(id_list[i], i);
}
for(String s : report) {
map.get(s.split(" ")[1]).add(s.split(" ")[0]);
}
for(int i = 0; i < id_list.length; i++) {
HashSet<String> set = map.get(id_list[i]);
if(set.size() >= k) {
for(String s : set) {
answer[indexMap.get(s)]++;
}
}
}
return answer;
}