Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

il - leetcode-26: Remove Duplicates from Sorted Array #49

Merged
merged 1 commit into from
Apr 22, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
5 changes: 5 additions & 0 deletions leetcode-study/leetcode-26/go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
module github.com/emahiro/il/leetcode-26

go 1.20

require golang.org/x/exp v0.0.0-20230420155640-133eef4313cb
2 changes: 2 additions & 0 deletions leetcode-study/leetcode-26/go.sum
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
golang.org/x/exp v0.0.0-20230420155640-133eef4313cb h1:rhjz/8Mbfa8xROFiH+MQphmAmgqRM0bOMnytznhWEXk=
golang.org/x/exp v0.0.0-20230420155640-133eef4313cb/go.mod h1:V1LtkGg67GoY2N1AnLN78QLrzxkLyJw7RJb1gzOOz9w=
5 changes: 5 additions & 0 deletions leetcode-study/leetcode-26/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
package main

import "fmt"

func main() { fmt.Println("hello world") }
60 changes: 60 additions & 0 deletions leetcode-study/leetcode-26/main_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
package main

import (
"testing"

"golang.org/x/exp/slices"
)

func uniqNormal(s *[]int) {
m := make(map[int]struct{})
for _, v := range *s {
m[v] = struct{}{}
}
*s = (*s)[:0]
for k := range m {
*s = append(*s, k)
}
}

func uniqFast(s *[]int) {
offset := 1
for i := 1; i < len(*s); i++ {
if (*s)[i] != (*s)[i-1] {
(*s)[offset] = (*s)[i]
offset++
}
}
*s = (*s)[:offset]
}

func uniqGen[T comparable](s *[]T) {
_ = slices.Compact(*s)
}

func Benchmark(b *testing.B) {
b.ReportAllocs()

list := []int{1, 1, 2, 2}

b.Run("unique normal", func(b *testing.B) {
b.ResetTimer()
for i := 0; i < b.N; i++ {
uniqNormal(&list)
}
})

b.Run("unique faster", func(b *testing.B) {
b.ResetTimer()
for i := 0; i < b.N; i++ {
uniqFast(&list)
}
})

b.Run("unique generic", func(b *testing.B) {
b.ResetTimer()
for i := 0; i < b.N; i++ {
uniqGen(&list)
}
})
}