๐Ÿค ์€์ง€log ๐Ÿค

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค:Javascript] ๋ฐฐ์—ด ๋งŒ๋“ค๊ธฐ 3 ๋ณธ๋ฌธ

๐ŸŒˆ ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค:Javascript] ๋ฐฐ์—ด ๋งŒ๋“ค๊ธฐ 3

Eun_zii 2024. 3. 22. 16:33

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค Lv.0

- ๋ฐฐ์—ด ๋งŒ๋“ค๊ธฐ 3

 

๐Ÿ’š ๋ฌธ์ œ์„ค๋ช…

  • ์ •์ˆ˜ ๋ฐฐ์—ด arr์™€ 2๊ฐœ์˜ ๊ตฌ๊ฐ„์ด ๋‹ด๊ธด ๋ฐฐ์—ด intervals๊ฐ€ ์ฃผ์–ด์ง‘๋‹ˆ๋‹ค. intervals๋Š” ํ•ญ์ƒ [[a1, b1], [a2, b2]]์˜ ๊ผด๋กœ ์ฃผ์–ด์ง€๋ฉฐ ๊ฐ ๊ตฌ๊ฐ„์€ ๋‹ซํžŒ ๊ตฌ๊ฐ„์ž…๋‹ˆ๋‹ค. ๋‹ซํžŒ ๊ตฌ๊ฐ„์€ ์–‘ ๋๊ฐ’๊ณผ ๊ทธ ์‚ฌ์ด์˜ ๊ฐ’์„ ๋ชจ๋‘ ํฌํ•จํ•˜๋Š” ๊ตฌ๊ฐ„์„ ์˜๋ฏธํ•ฉ๋‹ˆ๋‹ค. ์ด๋•Œ ๋ฐฐ์—ด arr์˜ ์ฒซ ๋ฒˆ์งธ ๊ตฌ๊ฐ„์— ํ•ด๋‹นํ•˜๋Š” ๋ฐฐ์—ด๊ณผ ๋‘ ๋ฒˆ์งธ ๊ตฌ๊ฐ„์— ํ•ด๋‹นํ•˜๋Š” ๋ฐฐ์—ด์„ ์•ž๋’ค๋กœ ๋ถ™์—ฌ ์ƒˆ๋กœ์šด ๋ฐฐ์—ด์„ ๋งŒ๋“ค์–ด return ํ•˜๋Š” solution ํ•จ์ˆ˜๋ฅผ ์™„์„ฑํ•ด ์ฃผ์„ธ์š”.

 

๐Ÿ’š ์ œํ•œ์กฐ๊ฑด

  • 1 ≤ arr์˜ ๊ธธ์ด ≤ 100,000
    • 1 ≤ arr์˜ ์›์†Œ < 100
  • 1 ≤ a1  b1 < arr์˜ ๊ธธ์ด
  • 1 ≤ a2  b2 < arr์˜ ๊ธธ์ด

 

๐Ÿ’š ํ’€์ด

function solution(arr, intervals) {
      let answer = [];
    for (let i = 0; i < intervals.length; i++) {
        const [a, b] = intervals[i];
        const slice = arr.slice(a, b + 1);
        answer = answer.concat(slice); 
    }
    return answer;
}

 

โœ… 

intervals ๊ฐ„๊ฒฉ์— ๋”ฐ๋ผ arr๋ฐฐ์—ด์˜ ๊ตฌ๊ฐ„์„ ์ €์žฅํ•  ๋นˆ ๋ฐฐ์—ด answer์„ ์„ ์–ธํ•ด์ค€๋‹ค.

for๋ฌธ์œผ๋กœ ์‚ฌ์šฉํ•ด์„œ intervals ๋ฐฐ์—ด์„ ๋ฐ˜๋ณตํ•ด์ค€๋‹ค. ๋ฐ˜๋ณตํ•˜๋Š” ๋™์•ˆ intervals ๋ฐฐ์—ด์—์„œ [ a, b ]๋ฅผ ๋ถ„ํ•ดํ•ด์ฃผ๊ณ , 

arr ๋ฐฐ์—ด์—์„œ ์ธ๋ฑ์Šค a ๋ถ€ํ„ฐ ์ธ๋ฑ์Šค b( +1์„ ์‚ฌ์šฉํ•ด์„œ b ํฌํ•จ ํ•ด์ค€๋‹ค. ) ๊นŒ์ง€ ์š”์†Œ๋ฅผ ์ถ”์ถœํ•œ๋‹ค.

( slice() ๋ฉ”์„œ๋“œ๋Š” ๋ฐฐ์—ด ์ผ๋ถ€์˜ ์–•์€ ๋ณต์‚ฌ๋ณธ์„ ์ƒˆ ๋ฐฐ์—ด ๊ฐ์ฒด๋กœ ๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค. )

 

concat( ) ๋ฉ”์„œ๋“œ๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ slice ๋ฐฐ์—ด์„ ๋นˆ๋ฐฐ์—ด answer ์— ์—ฐ๊ฒฐํ•ด์ค€๋‹ค.

( concat() ๋ฉ”์†Œ๋“œ๋Š” ๋‘ ๊ฐœ ์ด์ƒ์˜ ๋ฐฐ์—ด์„ ๋ณ‘ํ•ฉํ•˜๋Š” ๋ฐ ์‚ฌ์šฉ๋ฉ๋‹ˆ๋‹ค. )

728x90