Poylib
기록형 프론트엔드
Poylib
전체 방문자
오늘
어제
  • 분류 전체보기 (91)
    • Programing (38)
      • Javascript (17)
      • Typescript (1)
      • React (9)
      • React-Native (6)
      • Git (4)
      • Next (1)
    • Study (36)
      • Algorithm (35)
      • Etc. (1)
    • Record (17)
      • Memoirs (12)
      • Group (5)

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

인기 글

태그

  • 알고리즘
  • 기초
  • react-native
  • Object
  • javascript
  • vite
  • react
  • Error
  • 코칭스터디
  • 리액트
  • typescript
  • 백준
  • 자바스크립트
  • 회고
  • Git
  • ReactNative
  • 코딩테스트
  • 프로그래머스

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
Poylib

기록형 프론트엔드

Study/Algorithm

[programmers / JavaScript] K번째 수

2022. 5. 6. 17:24
https://programmers.co.kr/learn/courses/30/lessons/42748

배열의 범위를 주고, 범위 내에서 k번째 수를 구하는 문제다. 처음엔 splice() 메서드를 사용했지만, splice()는 원본 배열을 변경시키기 때문에 slice() 메서드를 이용해 풀었다.

sol 1

const array = [1, 5, 2, 6, 3, 7, 4];
const commands = [[2, 5, 3], [4, 4, 1], [1, 7, 3]];

function solution(array,commands) {
  let answer = [];
  commands.forEach(v => {
    const arr = array.slice(v[0]-1,v[1]);
    arr.sort((a,b) => a-b);
    answer.push(arr[v[2]-1]);
  })
  return answer
}
console.log(solution(array,commands)) //[ 5, 6, 3 ]

For문보다는 forEach 메서드를 이용해 풀어보았다. forEach 메서드는 for 문에 비해 성능이 좋지는 않지만 가독성이 더 좋다고 한다. 시간이 많이 걸리는 복잡한 코드 또는 높은 성능이 필요한 경우가 아니라면 for 문 대신 forEach 메서드를 사용할 것을 권장한다. ( 출처 : deep dive)

 

sol 2

const array = [1, 5, 2, 6, 3, 7, 4];
const commands = [[2, 5, 3], [4, 4, 1], [1, 7, 3]];


function solution(array, commands) {
  return commands.map(answer => {
    const [sPosition,ePosition,position] = answer
    const newArr = array
    .filter((v,i) => i>=sPosition-1 && i<=ePosition-1)
    .sort((a,b) => a-b)
    
    return newArr[position-1]
  })
}
console.log(solution(array,commands)) // [ 5, 6, 3 ]

구조분해할당으로 쪼개서 받은 후 filter 메서드를 이용해 범위를 지정한다. 배열 메서드를 잘 활용한 좋은 풀이인 것 같다.

저작자표시 비영리 변경금지 (새창열림)

'Study > Algorithm' 카테고리의 다른 글

<BEAKJOON / node.js> 11047 동전 0  (0) 2022.05.22
<programmers / JavaScript> 로또의 최고 순위와 최저 순위  (0) 2022.05.18
[BEAKJOON / node.js] 5533 유니크  (0) 2022.05.02
[programmers / JavaScript] 숫자 문자열과 영단어  (0) 2022.04.30
<BEAKJOON / node.js> 10828 스택  (0) 2022.04.29
    'Study/Algorithm' 카테고리의 다른 글
    • <BEAKJOON / node.js> 11047 동전 0
    • <programmers / JavaScript> 로또의 최고 순위와 최저 순위
    • [BEAKJOON / node.js] 5533 유니크
    • [programmers / JavaScript] 숫자 문자열과 영단어
    Poylib
    Poylib
    모시깽 기록

    티스토리툴바