Home > 2024 > Leet-Code > πŸ“ λ°°μ—΄ μ‚½μž… 3(λ°°μ—΄μ˜ 아무 κ³³μ—λ‚˜ μ‚½μž…ν•˜κΈ° - Inserting Anywhere in the Array)

πŸ“ λ°°μ—΄ μ‚½μž… 3(λ°°μ—΄μ˜ 아무 κ³³μ—λ‚˜ μ‚½μž…ν•˜κΈ° - Inserting Anywhere in the Array)
swift algorithm datastructure

λ°°μ—΄ μ‚½μž… μ‹œλ¦¬μ¦ˆ

λ°°μ—΄ μ‚½μž…1 (λ°°μ—΄μ˜ 끝에 μ‚½μž…ν•˜κΈ°-Inserting at the End of an Array)

λ°°μ—΄ μ‚½μž…2 (λ°°μ—΄μ˜ μ‹œμž‘ 뢀뢄에 μ‚½μž…ν•˜κΈ° - Inserting at the Start of an Array)


λ§ˆμ°¬κ°€μ§€λ‘œ, 주어진 μΈλ±μŠ€μ— μ‚½μž…ν•˜κΈ° μœ„ν•΄μ„œλŠ”, ν•΄λ‹Ή μΈλ±μŠ€λΆ€ν„° μ‹œμž‘ν•˜λŠ” λͺ¨λ“  μš”μ†Œλ“€μ„ 였λ₯Έμͺ½μœΌλ‘œ ν•œ μžλ¦¬μ”© μ΄λ™μ‹œμΌœμ•Ό ν•©λ‹ˆλ‹€.

μƒˆ μš”μ†Œλ₯Ό μœ„ν•œ 곡간이 μƒμ„±λ˜λ©΄, μ‚½μž…μ„ μ§„ν–‰ν•©λ‹ˆλ‹€.

생각해보면, μ‹œμž‘ 뢀뢄에 μ‚½μž…ν•˜λŠ” 것은 사싀 주어진 μΈλ±μŠ€μ— μš”μ†Œλ₯Ό μ‚½μž…ν•˜λŠ” κ²ƒμ˜ νŠΉλ³„ν•œ κ²½μš°μ— ν•΄λ‹Ήν•©λ‹ˆλ‹€.

κ·Έ κ²½μš°μ— 주어진 μΈλ±μŠ€λŠ” 0μ΄μ—ˆμŠ΅λ‹ˆλ‹€.






λ‹€μ‹œ ν•œ 번 λ§μ”€λ“œλ¦¬μ§€λ§Œ, 이것도 λΉ„μš©μ΄ 많이 λ“œλŠ” μž‘μ—…μž…λ‹ˆλ‹€.

μƒˆ μš”μ†Œλ₯Ό μ‹€μ œλ‘œ μ‚½μž…ν•˜κΈ° 전에 거의 λͺ¨λ“  λ‹€λ₯Έ μš”μ†Œλ“€μ„ 였λ₯Έμͺ½μœΌλ‘œ μ΄λ™μ‹œμΌœμ•Ό ν•  μˆ˜λ„ 있기 λ•Œλ¬Έμž…λ‹ˆλ‹€.

μœ„μ—μ„œ 보셨듯이, λ§Žμ€ μš”μ†Œλ“€μ„ 였λ₯Έμͺ½μœΌλ‘œ ν•œ μΉΈμ”© μ΄λ™μ‹œν‚€λŠ” 것은 μ‚½μž… μž‘μ—…μ˜ μ‹œκ°„ λ³΅μž‘λ„λ₯Ό μ¦κ°€μ‹œν‚΅λ‹ˆλ‹€.



λ‹€μŒμ€ μ½”λ“œμ˜ λͺ¨μŠ΅μž…λ‹ˆλ‹€

// λ°°μ—΄ μ‚½μž… 1,2 μ½”λ“œ μ°Έκ³ 
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


for i in(0...3).reversed() {
	intArray[i + 1] = intArray[i]
}

intArray[0] = 20

// 인덱슀 2에 μš”μ†Œλ₯Ό μ‚½μž…ν•˜κ³  μ‹Άλ‹€κ³  κ°€μ •ν•΄λ΄…μ‹œλ‹€.
// λ¨Όμ €, μƒˆλ‘œμš΄ μš”μ†Œλ₯Ό μœ„ν•œ 곡간을 λ§Œλ“€μ–΄μ•Ό ν•©λ‹ˆλ‹€.
for i in stride(from: 4, through: 2, by: -1) {
	// 각 μš”μ†Œλ₯Ό 였λ₯Έμͺ½μœΌλ‘œ ν•œ μœ„μΉ˜μ”© μ΄λ™μ‹œν‚΅λ‹ˆλ‹€.
	intArray[i + 1] = intArray[i]
}

// 이제 μƒˆλ‘œμš΄ μš”μ†Œλ₯Ό μœ„ν•œ 곡간을 λ§Œλ“€μ—ˆμœΌλ―€λ‘œ,
// ν•„μš”ν•œ μΈλ±μŠ€μ— μ‚½μž…ν•  수 μžˆμŠ΅λ‹ˆλ‹€.
intArray[2] = 30

printArray()

λ‹€μŒμ€ printArrayλ₯Ό μ‹€ν–‰ν•œ κ²°κ³Όμž…λ‹ˆλ‹€.

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

μ£Όμ˜ν•΄μ•Ό ν•  μ£Όμš”ν•œ 것은 array.capacityκ°€ λ² μ—΄μ˜ 전체 μš©λŸ‰μ„ μ œκ³΅ν•œλ‹€λŠ” 점을 κΈ°μ–΅ν•˜λŠ” κ²ƒμž…λ‹ˆλ‹€.
λ§ˆμ§€λ§‰μœΌλ‘œ μ‚¬μš©λœ μŠ¬λ‘―μ„ μ•Œκ³  μ‹Άλ‹€λ©΄ count λ³€μˆ˜λ₯Ό μ‚¬μš©ν•˜μ—¬ 직접 μΆ”μ ν•΄μ•Όν•©λ‹ˆλ‹€.