Java & Spring/코딩테스트

6일차 - 알고리즘 코드카타

DJ.Kang 2024. 7. 22. 11:14

- 진행

일자 완료 번호
24.07.16 1~20
24.07.17 21~35
24.07.18 36~42
24.07.19 43~47
24.07.22 48~50

 

- 회고

48. K번째수

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

 

프로그래머스

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

programmers.co.kr

- 풀이과정

import java.util.*;
class Solution {
    public int[] solution(int[] array, int[][] commands) {
		int[] answer = new int[commands.length];
		
		for(int a = 0; a < commands.length; a++) {
				int i = commands[a][0] - 1;
				int j = commands[a][1] - 1;
				int k = commands[a][2] - 1;
				int[] tmp = new int[j - i + 1];
				for(int b = 0; b < tmp.length; b++) {
					tmp[b] = array[b + i];
			}
				Arrays.sort(tmp);
				answer[a] = tmp[k];
		}
        return answer;
    }
}
  1. commands 배열을 반복문을 통해 순회
  2. 변수 i, j, k를 commands배열에서 가져와 대입
  3. tmp배열에 i부터 j까지 배열 복사
  4. Arrays.sort()메서드를 사용하여 배열 정렬
  5. tmp의 k번째 원소를 answer배열에 대입(commands와 answer의 인덱스가 한 반복문을 통해 가능)

- 다른방법

import java.util.Arrays;
class Solution {
    public int[] solution(int[] array, int[][] commands) {
        int[] answer = new int[commands.length];

        for(int i=0; i<commands.length; i++){
            int[] temp = Arrays.copyOfRange(array, commands[i][0]-1, commands[i][1]);
            Arrays.sort(temp);
            answer[i] = temp[commands[i][2]-1];
        }
        return answer;
    }
}
  1. 정답 배열 answer을 commands의 길이 크기로 선언
  2. Arrays.copyOfRange() 메서드 사용하여 원본 배열의 일부분을 복사하여 temp배열 생성
  3. Arrays.sort()를 사용하여 temp 배열 정렬
  4. answer배열에 temp배열 k번째 원소(commands[i][2]-1) 대입

50. 가장 가까운 다른 글자

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

 

프로그래머스

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

programmers.co.kr

- 풀이과정

import java.util.*;
class Solution {
    public int[] solution(String s) {
		Map<String, Integer> map = new HashMap<>();
		int[] answer = new int [s.length()];
		
		for(int i = 0; i < s.length(); i++) {
			String c  = Character.toString(s.charAt(i));
			if(!map.containsKey(c)) {
				map.put(c, i);
				answer[i] = -1;
			}else {
				answer[i] = i - map.get(c);
				map.put(c, i);
			}
		}
        return answer;
    }
}
  1. map을 사용하여 각 단어를 key값으로 그 단어의 위치(index)를 value값으로 대입하여 풀면 되겠다고 생각함
  2. 입력 문자열 s의 길이만큼의 answer배열 생성
  3. for문을 통해 각 단어와 인덱스를 map에 저장
  4. map.containsKey()메서드를 통해 해당 단어(key)가 map에 존재하는지 확인
  5. 존재하지않으면 answer[i]에 -1을 대입
  6. 존재하면 answer[i]에 i - (해당 key의 value값)(가장 가까운 이전 위치) 대입

※ 개선 가능한 부분 : 위 코드에 보면 map.put(c, i)가 조건에 상관없이 들어가므로 if문 밖으로 꺼낼 수 있을거 같다고 생각

→ 위치가 중요, 만약 if문 위로 빼게되면 map.containkey()가 항상 true가 되게되어 처음등장한 값을 구별 할 수없음

- map 설명 자료 : https://djhelloworld.tistory.com/93

 

Map 기본 문법 및 사용법

선언 및 초기화Map map = new HashMap();으로 선언 및 초기화 하며 key와 value의 type을 정해주면된다.import java.util.HashMap;import java.util.Map;public class Main { public static void main(String[] args) { Map map = new HashMap(); }}

djhelloworld.tistory.com