Problem solving/Algorithms

Kth Number (K번째 수)

Young_A 2020. 8. 27. 02:42
Question

You need to get the Kth number from an array that is between the Ith number and the Jth number in the given array.

For example, if the given array = [1, 5, 2, 6, 3, 7, 4], i = 2, j = 5, and k = 3,

  1. [5, 2, 6, 3] is the array from the 2nd number to 5th number in the given array
  2. The array from the first step can be arranged in order ascending as [2, 3, 5, 6]
  3. 5 is the 3rd number in the array from the second step.

When the array named as 'array' and the two-dimensional array named as 'commands' which includes an element [i, j, k], return a result array that calculates as above all of the elements in commands.

 

Limitation
  • The length of 'array' can be more than or equal to 1 and less than or equal to 100.
  • Each element in 'array' can be more than or equal to 1 and less than or equal to 100.
  • The length of 'commands' can be more than or equal to 1 and less than or equal to 50.
  • The length of each element in 'commands' is 3.

 

Example of I/O
array commands return
[1, 5, 2, 6, 3, 7, 4] [[2, 5, 3], [4, 4, 1], [1, 7, 3]] [5, 6, 3]

 

My Solution
def solution(array, commands):
    answer = []
    for x in commands:
        i = x[0] - 1
        j = x[1]
        k = x[2]
        
        sorted_array = array[i:j]
        sorted_array.sort()
        answer.append(sorted_array[k-1])

    return answer

 

Reference

프로그래머스 코딩테스트 연습 - K번째수

 

코딩테스트 연습 - K번째수

[1, 5, 2, 6, 3, 7, 4] [[2, 5, 3], [4, 4, 1], [1, 7, 3]] [5, 6, 3]

programmers.co.kr