알고리즘/LeetCode
[LeetCode] 26. Remove Duplicates from Sorted Array [GoLang, Python]
Jeff Hwang
2019. 3. 31. 03:25
https://leetcode.com/problems/remove-duplicates-from-sorted-array/
Remove Duplicates from Sorted Array - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
[GoLang 풀이]
package main
import "fmt"
func main() {
nums := []int{1, 1, 2}
removeDuplicates(nums)
}
func removeDuplicates(nums []int) int {
// nums 의 길이
var ln int = len(nums)
// nums 의 index 나타내는 변수
var i int = 1
// out of range exception 을 처리할 함수
func() {
// 예외가 발생할시 알림을 알리고 그 다음 문장을 실행
rec := recover()
fmt.Println(rec)
}()
// i가 nums의 길이보다 작을때까지 반복
for i < ln {
// nums[i] 와 nums[i-1] 이 같으면 nums에서 빼낸다
if nums[i-1] != nums[i] {
i++
} else {
// nums[0~i : i+1 ~ 끝까지] nums에 append 한다
nums = append(nums[:i], nums[i+1:]...)
// 원소 하나를 집어넣지 않았으므로 전체길이는 1이 감소
ln--
}
}
// return ln
return ln
}
[Python 풀이]
class Solution(object): def removeDuplicates(self, nums): # nms의 길이 ln = len(nums) # index 변수 i = 1 # 문제에서 새로운 array 를 생성하지 말고 # nums를 활용하라고 함 # try-catch 문으로 처리하여 # out of range exception 이 발생할 상황을 예방 try: # i가 nums의 길이보다 작을 때까지 반복 while i < ln: # nums i 가 이전 원소와 같다면 # i 번째 원소를 pop 한다 if nums[i] == nums[i-1]: nums.pop(i) # pop을 하였으니 nums 의 길이는 1 작아진다 ln -= 1 # 밑에 부분을 실행하지않고 반복문의 처음으로 간다. continue # 이전 원소와 같지 않다면 인덱스를 증가 i += 1 except: # out of range exception 이 발생시 ln을 리턴 return ln # 무사히 반복문을 빠져나오면 ln 리턴 return ln