Algorithm

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค ์ •๋ ฌ Lv1 <K๋ฒˆ์งธ์ˆ˜> JAVA

seulye 2021. 8. 25. 20:57

๋ฌธ์ œ ์„ค๋ช…
๋ฐฐ์—ด array์˜ i๋ฒˆ์งธ ์ˆซ์ž๋ถ€ํ„ฐ j๋ฒˆ์งธ ์ˆซ์ž๊นŒ์ง€ ์ž๋ฅด๊ณ  ์ •๋ ฌํ–ˆ์„ ๋•Œ, k๋ฒˆ์งธ์— ์žˆ๋Š” ์ˆ˜๋ฅผ ๊ตฌํ•˜๋ ค ํ•ฉ๋‹ˆ๋‹ค.
์˜ˆ๋ฅผ ๋“ค์–ด array๊ฐ€ [1, 5, 2, 6, 3, 7, 4], i = 2, j = 5, k = 3์ด๋ผ๋ฉด

  1. array์˜ 2๋ฒˆ์งธ๋ถ€ํ„ฐ 5๋ฒˆ์งธ๊นŒ์ง€ ์ž๋ฅด๋ฉด [5, 2, 6, 3]์ž…๋‹ˆ๋‹ค.
  2. 1์—์„œ ๋‚˜์˜จ ๋ฐฐ์—ด์„ ์ •๋ ฌํ•˜๋ฉด [2, 3, 5, 6]์ž…๋‹ˆ๋‹ค.
  3. 2์—์„œ ๋‚˜์˜จ ๋ฐฐ์—ด์˜ 3๋ฒˆ์งธ ์ˆซ์ž๋Š” 5์ž…๋‹ˆ๋‹ค.

๋ฐฐ์—ด array, [i, j, k]๋ฅผ ์›์†Œ๋กœ ๊ฐ€์ง„ 2์ฐจ์› ๋ฐฐ์—ด commands๊ฐ€ ๋งค๊ฐœ๋ณ€์ˆ˜๋กœ ์ฃผ์–ด์งˆ ๋•Œ, commands์˜ ๋ชจ๋“  ์›์†Œ์— ๋Œ€ํ•ด ์•ž์„œ ์„ค๋ช…ํ•œ ์—ฐ์‚ฐ์„ ์ ์šฉํ–ˆ์„ ๋•Œ ๋‚˜์˜จ ๊ฒฐ๊ณผ๋ฅผ ๋ฐฐ์—ด์— ๋‹ด์•„ return ํ•˜๋„๋ก solution ํ•จ์ˆ˜๋ฅผ ์ž‘์„ฑํ•ด์ฃผ์„ธ์š”.
์ œํ•œ์‚ฌํ•ญ

  • array์˜ ๊ธธ์ด๋Š” 1 ์ด์ƒ 100 ์ดํ•˜์ž…๋‹ˆ๋‹ค.
  • array์˜ ๊ฐ ์›์†Œ๋Š” 1 ์ด์ƒ 100 ์ดํ•˜์ž…๋‹ˆ๋‹ค.
  • commands์˜ ๊ธธ์ด๋Š” 1 ์ด์ƒ 50 ์ดํ•˜์ž…๋‹ˆ๋‹ค.
  • commands์˜ ๊ฐ ์›์†Œ๋Š” ๊ธธ์ด๊ฐ€ 3์ž…๋‹ˆ๋‹ค.


์ž…์ถœ๋ ฅ ์˜ˆ

arraycommandsreturn

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



์ž…์ถœ๋ ฅ ์˜ˆ ์„ค๋ช…

[1, 5, 2, 6, 3, 7, 4]๋ฅผ 2๋ฒˆ์งธ๋ถ€ํ„ฐ 5๋ฒˆ์งธ๊นŒ์ง€ ์ž๋ฅธ ํ›„ ์ •๋ ฌํ•ฉ๋‹ˆ๋‹ค. [2, 3, 5, 6]์˜ ์„ธ ๋ฒˆ์งธ ์ˆซ์ž๋Š” 5์ž…๋‹ˆ๋‹ค.
[1, 5, 2, 6, 3, 7, 4]๋ฅผ 4๋ฒˆ์งธ๋ถ€ํ„ฐ 4๋ฒˆ์งธ๊นŒ์ง€ ์ž๋ฅธ ํ›„ ์ •๋ ฌํ•ฉ๋‹ˆ๋‹ค. [6]์˜ ์ฒซ ๋ฒˆ์งธ ์ˆซ์ž๋Š” 6์ž…๋‹ˆ๋‹ค.
[1, 5, 2, 6, 3, 7, 4]๋ฅผ 1๋ฒˆ์งธ๋ถ€ํ„ฐ 7๋ฒˆ์งธ๊นŒ์ง€ ์ž๋ฆ…๋‹ˆ๋‹ค. [1, 2, 3, 4, 5, 6, 7]์˜ ์„ธ ๋ฒˆ์งธ ์ˆซ์ž๋Š” 3์ž…๋‹ˆ๋‹ค.

import java.util.Arrays; class Solution { public int[] solution(int[] array, int[][] commands) { int clen=commands.length; int[] answer = new int[clen]; int from; int to; int seq; int len; for (int i=0;i<clen;i++){ from = commands[i][0]; to = commands[i][1]; seq = commands[i][2]; len=to-from+1; int [] arr = new int[len]; for (int j=0;j<len;j++){ arr[j]=array[j+from-1]; } Arrays.sort(arr); answer[i]=arr[seq-1]; } return answer; } }