Home > Archive > Leet-Code > ๐Ÿ“ ๋ฐฐ์—ด ์‚ฝ์ž… 1(๋ฐฐ์—ด์˜ ๋์— ์‚ฝ์ž…ํ•˜๊ธฐ-Inserting at the End of an Array)

๐Ÿ“ ๋ฐฐ์—ด ์‚ฝ์ž… 1(๋ฐฐ์—ด์˜ ๋์— ์‚ฝ์ž…ํ•˜๊ธฐ-Inserting at the End of an Array)
algorithm datastructure

๋ฐฐ์—ด์— ์ƒˆ๋กœ์šด ์š”์†Œ๋ฅผ ์‚ฝ์ž…ํ•˜๋Š” ๊ฒƒ์€ ์—ฌ๋Ÿฌ ํ˜•ํƒœ๋ฅผ ๊ฐ€์งˆ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค:


  1. ๋ฐฐ์—ด์˜ ๋์— ์ƒˆ ์š”์†Œ๋ฅผ ์‚ฝ์ž…ํ•˜๊ธฐ.
  2. ๋ฐฐ์—ด์˜ ์‹œ์ž‘ ๋ถ€๋ถ„์— ์ƒˆ ์š”์†Œ๋ฅผ ์‚ฝ์ž…ํ•˜๊ธฐ.
  3. ๋ฐฐ์—ด ๋‚ด์˜ ์ฃผ์–ด์ง„ ์ธ๋ฑ์Šค์— ์ƒˆ ์š”์†Œ๋ฅผ ์‚ฝ์ž…ํ•˜๊ธฐ.

๋ฐฐ์—ด์˜ ๋์— ์‚ฝ์ž…ํ•˜๊ธฐ(Inserting at the End of an Array).

์–ด๋Š ์‹œ์ ์—์„œ๋“ , ์šฐ๋ฆฌ๋Š” length ๋ณ€์ˆ˜์— ์ถ”์ ํ•ด๋‘” ๋ฐฐ์—ด์˜ ๋งˆ์ง€๋ง‰ ์š”์†Œ์˜ ์ธ๋ฑ์Šค๋ฅผ ์•Œ๊ณ  ์žˆ์Šต๋‹ˆ๋‹ค.

๋์— ์š”์†Œ๋ฅผ ์‚ฝ์ž…ํ•˜๊ธฐ ์œ„ํ•ด ํ•ด์•ผ ํ•  ์ผ์€ ํ˜„์žฌ ๋งˆ์ง€๋ง‰ ์š”์†Œ ๋‹ค์Œ ์ธ๋ฑ์Šค์— ์ƒˆ ์š”์†Œ๋ฅผ ํ• ๋‹นํ•˜๋Š” ๊ฒƒ๋ฟ์ž…๋‹ˆ๋‹ค.






์ด๊ฒƒ์€ ์šฐ๋ฆฌ๊ฐ€ ์ด๋ฏธ ๋ณธ ๊ฒƒ๊ณผ ๊ฑฐ์˜ ๊ฐ™์Šต๋‹ˆ๋‹ค.

์ตœ๋Œ€ 6๊ฐœ์˜ ํ•ญ๋ชฉ์„ ๋‹ด์„ ์ˆ˜ ์žˆ๋Š” ์ƒˆ ๋ฐฐ์—ด์„ ๋งŒ๋“ค๊ณ , ๊ทธ ๋‹ค์Œ ์ฒซ 3๊ฐœ์˜ ์ธ๋ฑ์Šค์— ํ•ญ๋ชฉ์„ ์ถ”๊ฐ€ํ•˜๋Š” ์ฝ”๋“œ์ž…๋‹ˆ๋‹ค.

// 6๊ฐœ์˜ ์š”์†Œ๋ฅผ ๊ฐ€์ง„ ์ •์ˆ˜ ๋ฐฐ์—ด ์„ ์–ธ
var intArray = [Int](repeating: 0, count: 6)
var length = 0

// ๋ฐฐ์—ด์— 3๊ฐœ์˜ ์š”์†Œ ์ถ”๊ฐ€
for i in 0..<3 {
    intArray[length] = i
    length += 1
}

์šฐ๋ฆฌ๊ฐ€ ๋ฌด์Šจ ์ผ์ด ์ผ์–ด๋‚˜๊ณ  ์žˆ๋Š”์ง€ ์‹œ๊ฐํ™”ํ•˜๋Š” ๋ฐ ๋„์›€์ด ๋˜๋Š” ํ•จ์ˆ˜, printArray๋ฅผ ์ •์˜ํ•ด๋ด…์‹œ๋‹ค.

for i in 0..<intArray.count {
    print("Index \(i) contains \(intArray[i])")
}

์šฐ๋ฆฌ๊ฐ€ printArray ํ•จ์ˆ˜๋ฅผ ์‹คํ–‰ํ•˜๋ฉด ๋‹ค์Œ๊ณผ ๊ฐ™์€ ์ถœ๋ ฅ์„ ์–ป์„ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

Index 0 contains 0.
Index 1 contains 1.
Index 2 contains 2.
Index 3 contains 0.
Index 4 contains 0.
Index 5 contains 0.

์ธ๋ฑ์Šค 3, 4, 5๊ฐ€ ๋ชจ๋‘ 0์„ ํฌํ•จํ•˜๊ณ  ์žˆ๋Š” ๊ฒƒ์„ ๋ณด์…จ๋‚˜์š”?

์ด๊ฒƒ์€ Swift๊ฐ€ ์‚ฌ์šฉํ•˜์ง€ ์•Š๋Š” int ๋ฐฐ์—ด ์Šฌ๋กฏ์„ 0์œผ๋กœ ์ฑ„์šฐ๊ธฐ ๋•Œ๋ฌธ์ž…๋‹ˆ๋‹ค.



์ด์ œ 4๋ฒˆ์งธ ์š”์†Œ๋ฅผ ์ถ”๊ฐ€ํ•ด๋ด…์‹œ๋‹ค. ์ˆซ์ž 10์„ ์ถ”๊ฐ€ํ•  ๊ฒƒ์ž…๋‹ˆ๋‹ค.

// ๋ฐฐ์—ด ๋์— ์ƒˆ ์š”์†Œ๋ฅผ ์‚ฝ์ž…. ๋‹ค์‹œ ํ•œ๋ฒˆ,
// ์ƒˆ ์š”์†Œ๋ฅผ ์‚ฝ์ž…ํ•˜๊ธฐ ์œ„ํ•ด ๋ฐฐ์—ด์— ์ถฉ๋ถ„ํ•œ ๊ณต๊ฐ„์ด ์žˆ๋Š”์ง€ ํ™•์ธํ•˜๋Š” ๊ฒƒ์ด ์ค‘์š”ํ•ฉ๋‹ˆ๋‹ค.
intArray[length] = 10
length += 1

๊ธธ์ด๋ฅผ 1 ์ฆ๊ฐ€์‹œํ‚จ ์ด์œ ๋ฅผ ์•Œ์•„์ฑ„์…จ๋‚˜์š”?

๊ธธ์ด๋ฅผ 1 ์ฆ๊ฐ€์‹œํ‚ค๋Š” ๊ฒƒ์ด ์ค‘์š”ํ•ฉ๋‹ˆ๋‹ค.

์ด ๋‹จ๊ณ„๋ฅผ ๊ฑด๋„ˆ ๋›ฐ๋ฉด ๋‹ค์Œ์— ๋‹ค๋ฅธ ์š”์†Œ๋ฅผ ์ถ”๊ฐ€ํ•  ๋•Œ ๋ฐฉ๊ธˆ ์ถ”๊ฐ€ํ•œ ์š”์†Œ๋ฅผ ์‹ค์ˆ˜๋กœ ๋ฎ์–ด์“ฐ๊ฒŒ ๋ฉ๋‹ˆ๋‹ค!

printArray๋ฅผ ๋‹ค์‹œ ์‹คํ–‰ํ•˜๋ฉด ๋‹ค์Œ๊ณผ ๊ฐ™์€ ๊ฒฐ๊ณผ๋ฅผ ์–ป์„ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

Index 0 contains 0.
Index 1 contains 1.
Index 2 contains 2.
Index 3 contains 10.
Index 4 contains 0.
Index 5 contains 0.