Go/Leet Code
Array101 Remove Duplicates from Sorted Array
Gopythor
2022. 3. 6. 22:00
728x90
반응형
My code
func removeDuplicates(nums []int) int {
if nums == nil {
return 0
}
k := 0
for _, v := range nums {
if v != nums[k] {
k++
nums[k] = v
}
}
return k + 1
}
- I used for loop value output.
- It starts from array[0].
- So if it will be different with value, k will be increased and value will be input there.
- Simple Code.
sample 0 ms submission
func removeDuplicates(nums []int) int {
if len(nums) < 2 {
return len(nums)
}
count := 0
for i := 1; i < len(nums); i++ {
if nums[count] != nums[i] {
count++
nums[count] = nums[i]
}
}
return count + 1
}
- This code does not process nums[0], so it will save time compared to my code.
sample 2 ms submission
func removeDuplicates(nums []int) int {
k := 0
for i:=0; i < len(nums)-1; i++ {
if nums[i] == nums[i + 1] {
continue
} else {
k++
temp := nums[i + 1]
nums[k] = temp
}
}
return k + 1
}
sample 3 ms submission
func removeDuplicates(nums []int) int {
if len(nums) < 1 {
return len(nums)
}
i := 0
for j := 1; j < len(nums); j++ {
if nums[i] != nums[j] {
nums[i+1] = nums[j]
i++
}
}
return i + 1
}
- I think this code also is not big difference.
sample 4300 KB submission
func removeDuplicates(nums []int) int {
idx := 0
for i:=0;i<len(nums);i++ {
for i+1<len(nums) && nums[i] == nums[i+1] {
i++
}
nums[idx] = nums[i]
idx++
}
return idx
}
- This code increments are two.
- First for loop is used for ranging array from start to end.
- Second for loop is used for cheking duplication between i and i+1.
- If i and i+1 are same, then increase i.
- When they find not duplication, value will be added to idx array and increase.
- Until they find duplication, i will increase.
- when i+1 is same with len(nums), last array will be added to idx array and finish loop.
- return qty.
sample 4400 KB submission
func removeDuplicates(nums []int) int {
count := 0
for i, _ := range nums {
if i == 0 {
count++
continue
} else if nums[i] != nums[i-1] {
nums[count] = nums[i]
count++
}
}
return count
}
- I think this is simple code.
- After increase, i will check between i and i-1.
- count is used for array.
728x90
반응형