Home > Archive > Leet-Code > ๐Ÿ“ ๋ฐฐ์—ด ์‚ฝ์ž… 2(๋ฐฐ์—ด์˜ ์‹œ์ž‘ ๋ถ€๋ถ„์— ์‚ฝ์ž…ํ•˜๊ธฐ - Inserting at the Start of an Array)

๐Ÿ“ ๋ฐฐ์—ด ์‚ฝ์ž… 2(๋ฐฐ์—ด์˜ ์‹œ์ž‘ ๋ถ€๋ถ„์— ์‚ฝ์ž…ํ•˜๊ธฐ - Inserting at the Start of an Array)
swift algorithm datastructure

๋ฐฐ์—ด ์‚ฝ์ž… ์‹œ๋ฆฌ์ฆˆ

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


๋ฐฐ์—ด์˜ ์‹œ์ž‘ ๋ถ€๋ถ„์— ์‚ฝ์ž…ํ•˜๊ธฐ(Inserting at the Start of an Array)

๋ฐฐ์—ด์˜ ์‹œ์ž‘ ๋ถ€๋ถ„์— ์š”์†Œ๋ฅผ ์‚ฝ์ž…ํ•˜๋ ค๋ฉด, ์ƒˆ ์š”์†Œ๋ฅผ ์œ„ํ•œ ๊ณต๊ฐ„์„ ๋งŒ๋“ค๊ธฐ ์œ„ํ•ด ๋ฐฐ์—ด์˜ ๋‹ค๋ฅธ ๋ชจ๋“  ์š”์†Œ๋“ค์„ ์˜ค๋ฅธ์ชฝ์œผ๋กœ ํ•˜๋‚˜์˜ ์ธ๋ฑ์Šค๋งŒํผ ์ด๋™์‹œ์ผœ์•ผ ํ•ฉ๋‹ˆ๋‹ค.

์ด๊ฒƒ์€ ๋น„์šฉ์ด ๋งค์šฐ ๋งŽ์ด ๋“œ๋Š” ์ž‘์—…์ž…๋‹ˆ๋‹ค, ์™œ๋ƒํ•˜๋ฉด ๊ธฐ์กด์˜ ์š”์†Œ๋“ค์„ ๋ชจ๋‘ ์˜ค๋ฅธ์ชฝ์œผ๋กœ ํ•œ ๋‹จ๊ณ„์”ฉ ์ด๋™์‹œ์ผœ์•ผ ํ•˜๊ธฐ ๋•Œ๋ฌธ์ž…๋‹ˆ๋‹ค.

๋ชจ๋“  ๊ฒƒ์„ ์ด๋™์‹œ์ผœ์•ผ ํ•œ๋‹ค๋Š” ๊ฒƒ์€ ์ด ์ž‘์—…์ด ์ƒ์ˆ˜ ์‹œ๊ฐ„ ์ž‘์—…์ด ์•„๋‹ˆ๋ผ๋Š” ๊ฒƒ์„ ์˜๋ฏธํ•ฉ๋‹ˆ๋‹ค.

์‚ฌ์‹ค, ๋ฐฐ์—ด์˜ ์‹œ์ž‘ ๋ถ€๋ถ„์— ์‚ฝ์ž…ํ•˜๋Š” ๋ฐ ๊ฑธ๋ฆฌ๋Š” ์‹œ๊ฐ„์€ ๋ฐฐ์—ด์˜ ๊ธธ์ด์— ๋น„๋ก€ํ•  ๊ฒƒ์ž…๋‹ˆ๋‹ค.

์‹œ๊ฐ„ ๋ณต์žก๋„ ๋ถ„์„ ์ธก๋ฉด์—์„œ ์ด๋Š” ์„ ํ˜• ์‹œ๊ฐ„ ๋ณต์žก๋„, ์ฆ‰ O(N)์ธ๋ฐ, ์—ฌ๊ธฐ์„œ N์€ ๋ฐฐ์—ด์˜ ๊ธธ์ด์ž…๋‹ˆ๋‹ค.






๋‹ค์Œ์€ ์ฝ”๋“œ์˜ ๋ชจ์Šต์ž…๋‹ˆ๋‹ค.

// ๋ฐฐ์—ด์‚ฝ์ž… 1 ์ฝ”๋“œ ์ฐธ๊ณ 
var intArray = [Int](repeating: 0, count: 6)
var length = 0


for i in 0..<3 {
	intArray[length] = i
	length += 1
}

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

intArray[length] = 10
length += 1

// ๋จผ์ €, ์ƒˆ๋กœ์šด ์š”์†Œ๋ฅผ ์œ„ํ•œ ๊ณต๊ฐ„์„ ๋งŒ๋“ค์–ด์•ผ ํ•ฉ๋‹ˆ๋‹ค.
// ์ด๋ฅผ ์œ„ํ•ด ๊ฐ ์š”์†Œ๋ฅผ ์˜ค๋ฅธ์ชฝ์œผ๋กœ ํ•˜๋‚˜์˜ ์ธ๋ฑ์Šค๋งŒํผ ์ด๋™์‹œํ‚ต๋‹ˆ๋‹ค.
// ์ด๊ฒƒ์€ ๋จผ์ € ์ธ๋ฑ์Šค 3์˜ ์š”์†Œ๋ฅผ ์ด๋™์‹œํ‚ค๊ณ , ๊ทธ ๋‹ค์Œ 2, ๊ทธ ๋‹ค์Œ 1, ๋งˆ์ง€๋ง‰์œผ๋กœ 0์„ ์ด๋™์‹œํ‚ต๋‹ˆ๋‹ค.
// ์–ด๋–ค ์š”์†Œ๋„ ๋ฎ์–ด์“ฐ์ง€ ์•Š๊ธฐ ์œ„ํ•ด ๋’ค์—์„œ๋ถ€ํ„ฐ ์ง„ํ–‰ํ•ด์•ผ ํ•ฉ๋‹ˆ๋‹ค.
for i in(0...3).reversed() {
    intArray[i + 1] = intArray[i]
}

// ์ด์ œ ์ƒˆ๋กœ์šด ์š”์†Œ๋ฅผ ์œ„ํ•œ ๊ณต๊ฐ„์„ ๋งŒ๋“ค์—ˆ์œผ๋ฏ€๋กœ,
// ์‹œ์ž‘ ๋ถ€๋ถ„์— ์‚ฝ์ž…ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.
intArray[0] = 20

printArray()

๋‹ค์Œ์€ printArray()๋ฅผ ์‹คํ–‰ํ•œ ๊ฒฐ๊ณผ์ž…๋‹ˆ๋‹ค.

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