Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 09a3ce2

Browse files
committed
970 finish
1 parent f5eac18 commit 09a3ce2

File tree

2 files changed

+42
-8
lines changed

2 files changed

+42
-8
lines changed

Algorithms/0970.powerful-integers/powerful-integers.go

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -39,15 +39,16 @@ func combine(ax, ay []int, bound int) []int {
3939

4040
func removeRepeated(nums []int) []int {
4141
sort.Ints(nums)
42-
res := make([]int, 1, len(nums))
43-
res[0] = nums[0]
44-
last := nums[0]
45-
for _, n := range nums {
46-
if n == last {
42+
43+
size := len(nums)
44+
45+
last, j := -1, -1
46+
for i := 0; i < size; i++ {
47+
if last == nums[i] { // nums[i]>0 for any i
4748
continue
4849
}
49-
res = append(res, n)
50-
last = n
50+
j++
51+
nums[j], last = nums[i], nums[i]
5152
}
52-
return res
53+
return nums[:j+1]
5354
}

Algorithms/0970.powerful-integers/powerful-integers_test.go

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,3 +64,36 @@ func Benchmark_powerfulIntegers(b *testing.B) {
6464
}
6565
}
6666
}
67+
68+
func Benchmark_removeRepeated(b *testing.B) {
69+
nums := []int{1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6, 7, 7, 7, 8, 8, 8, 9, 9, 9}
70+
for i := 1; i < b.N; i++ {
71+
removeRepeated(nums)
72+
}
73+
}
74+
75+
func Benchmark_removeRepeated2(b *testing.B) {
76+
nums := []int{1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6, 7, 7, 7, 8, 8, 8, 9, 9, 9}
77+
for i := 1; i < b.N; i++ {
78+
removeRepeated2(nums)
79+
}
80+
}
81+
82+
func removeRepeated2(nums []int) []int {
83+
sort.Ints(nums)
84+
85+
size := len(nums)
86+
if size == 0 {
87+
return nums
88+
}
89+
90+
i := 0
91+
for j := 1; j < size; j++ {
92+
if nums[i] == nums[j] {
93+
continue
94+
}
95+
i++
96+
nums[i] = nums[j]
97+
}
98+
return nums[:i+1]
99+
}

0 commit comments

Comments
 (0)