Algorithm
-
프로그래머스 - [카카오 인턴] 키패드 누르기Algorithm 2023. 5. 6. 00:21
문제 풀이 카카오 인턴쉽 문제답게 상당히 어려운 문제였다. 풀고자 했던 의도는 키패드를 먼저 2차원 평면 좌표로 구현하기 위해 2차원 배열로 좌표들을 지정해 주었고, 현재 왼손 시작 좌표, 오른손 시작 좌표를 지정해 준 다음 numbers 배열들을 좌표에 매칭시켰다. 먼저 1번, 4번, 7번에 해당되는 (1, 0), (2, 0), (3, 0)일 때 "L"을 추가하고 3번, 6번, 9번에 해당되는 (1, 2), (2, 2), (3, 2)일 때 "R"을 추가시킨다. 남은 0번, 2번, 5번, 8번을 처리할 때가 관건인데 이는 예시를 통해 이해해보자 왼손 위치가 키패드4번, 오른손 위치가 키패드9번에 있을 때 다음으로 5번 키를 눌러야 하는 상황 9번에서 5번을 가기위해 걸리는 거리는 (1,2)와 (2,1)사..
-
프로그래머스 - 두 개 뽑아서 더하기Algorithm 2023. 5. 4. 20:10
문제 풀이 풀고자 했던 의도는 단순하게 2중으로 배열을 순회하면 된다고 생각했다. 단 첫 번째 numbers 배열 안에서 순회되는 두번째 배열은 첫 번째 배열의 인덱스와 다른 인덱스 값과 더해야 하고, 이를 반복하면 2차원 배열이 결과값으로 나오기 때문에 flat 메서드로 1차원 배열로 변환해준 다음 중복값 제거와 정렬을 진행해준다 입출력 예제 2번을 예를 들어 보면 [5, 0, 2, 7] 배열을 순회하는데 5를 순회할 때는 [0, 2, 7], 0은 [5, 2, 7], 2는 [5, 0, 7], 7은 [5, 0, 2] 이런식으로 순회하는 인덱스를 제거한 배열들과 합을 구하는 것이다
-
프로그래머스 - 짝지어 제거하기Algorithm 2023. 5. 2. 18:08
문제 풀이 풀고자 했던 의도는 입력받은 문자열을 배열로 변환한 뒤 해당 배열을 순회하면서 배열의 idx번째 값과 idx+1 값을 비교해서 같다면 splice(idx, 2)로 제거한 뒤 idx값을 0으로 초기화 하려고 했다. 하지만 예상치 못한 문제가 있었는데, 그것은 코드는 제대로 작동 할지라도 비교할 배열 인덱스를 0으로 초기화하는 덕에 최악의 경우 O(n^2)의 시간복잡도를 가지게 된다는 것이었다. 다른 풀이방법을 모색하던 도중 stack 방식으로 풀면 O(n)의 시간복잡도로 해결할 수 있다는 힌트를 얻어 다시 풀어보았다. 입력받은 문자열을 splitedString 배열로 변환하고, 새로운 빈 answer 배열에다가 하나씩 push하면서 splitedString배열의 요소와 answer배열의 마지막 ..
-
프로그래머스 - 추억점수Algorithm 2023. 4. 27. 18:47
문제 풀이 풀고자 했던 의도는 받은 2차원 photo 배열의 각 배열의 요소들이 name 배열의 요소와 일치하는지 확인, 일치한다면 해당 name 배열의 index값들을 가져와 yearning 배열에서 가져온 index들에 일치하는 값들의 합을 answer배열에 하나씩 대입하는 것이었다. 의도대로 하드코딩을 해본 결과 답은 나왔지만 심히 지저분해서 화가 나지 않을 수가 없는 코드다. 지저분한 코드 줄이기 작업을 해보자... photo 배열의 요소를 name 배열의 요소와 비교해 얻은 인덱스값을 yearning 배열에 대입해 값을 뽑아내는게 키포인트다. reduce와 indexOf 함수를 이용해 photoArray의 요소를 name과 비교하고 그 결과값을 yearning에 바로 대입해주었다. 주목할 포인트..