27. Remove Element
문제 설명
[Int]
배열이 주어짐- 해당 배열에서
val
과 같은값을 삭제!inout
으로 선언되었으니 원본도 변경해주어라
문제 풀이
- 내가 걱정했던 거는 예시로 나와있는 다음과 같은 배열이다
[0,1,4,0,3,_,_,_]
- 이걸 구현하려면 어떻게 타입선언을 해줘야하지? 일단 nums는 [Int]로 선언이 되어있는데? 라고 생각했는데, 그냥 없어진걸 저렇게 표현한 것이었다. [0,1,4,0,3]만 만들면 되는 것이었다. 처음엔 그걸 모르고
class Solution {
func removeElement(_ nums: inout [Int], _ val: Int) -> Int {
nums = nums.map {
i in if i == val {
return 77
}
return i
}
print(nums)
return 1
}
}
var nums = [3, 2, 2, 3]
Solution().removeElement(&nums, 3)
이렇게 일단 77로 변경을 해줘봤더니
[77, 2, 2, 77]
잘 정리가 된 것을 알 수 있다. 대신 이게 순서는 상관없다했으니 타입만 잘 맞춰주면될 듯? (지금은 [Int]맞춰줘야해서 일단 77로 변경해본 것..
class Solution {
func removeElement(_ nums: inout [Int], _ val: Int) -> Int {
var answer = [Character]()
var cnt = 0
for num in nums {
if num == val {
answer.append("_")
}
else {
answer.append(Character(String(num)))
cnt += 1
}
}
return cnt
}
}
이거는 일단 있는 코드에서 수정해서 답이 맞는지 판단한 코드
class Solution {
func removeElement(_ nums: inout [Int], _ val: Int) -> Int {
var answer = [Character]()
var cnt = 0
for num in nums {
if num == val {
answer.append("_")
}
else {
answer.append(Character(String(num)))
cnt += 1
}
}
return cnt
}
}
최종 제출 코드
결국 엄청 간결하게 될 것 같아서 수정해주었다.
class Solution {
func removeElement(_ nums: inout [Int], _ val: Int) -> Int {
nums = nums.filter { $0 != val }
return nums.count
}
}
타인의 코드
class Solution {
func removeElement(_ nums: inout [Int], _ val: Int) -> Int {
var copy = nums
var resultIndex = 0
var valueCount = 0
while copy.count > 0 {
let current = copy.removeFirst()
if current != val {
nums[resultIndex] = current
resultIndex += 1
} else {
valueCount += 1
}
}
return nums.count - valueCount
}
}
원본에 바로 반영을 시켜줘야하니까 나는 Nums를 가져온 그대로 가공시켜줄 생각을 했는데, 있는 배열을 앞에서부터 하나씩 뜯어보면서 순서 상관없다는 것을 잘 이용한 코드엿던 것 같다.