-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(LeetCode #26): remove duplicates from sorted array
- Loading branch information
Angelica Hjelm Gardner
committed
Jan 19, 2025
1 parent
8e3536a
commit a56ceca
Showing
2 changed files
with
46 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,20 @@ | ||
package leetcode | ||
|
||
// Time complexity: O(n) | ||
// Space complexity: O(1) | ||
func RemoveDuplicates(nums []int) int { | ||
if len(nums) == 0 { | ||
return 0 | ||
} | ||
|
||
uniqueElements := 1 | ||
|
||
for i := 1; i < len(nums); i++ { | ||
if nums[i] != nums[i-1] { | ||
nums[uniqueElements] = nums[i] | ||
uniqueElements++ | ||
} | ||
} | ||
|
||
return uniqueElements | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,26 @@ | ||
package leetcode | ||
|
||
import "testing" | ||
|
||
func TestRemoveDuplicates(t *testing.T) { | ||
var tests = []struct { | ||
name string | ||
input []int | ||
expected []int | ||
output int | ||
}{ | ||
{"Short array", []int{1, 1, 2}, []int{1, 2}, 2}, | ||
{"Longer array", []int{0, 0, 1, 1, 1, 2, 2, 3, 3, 4}, []int{0, 1, 2, 3, 4}, 5}, | ||
{"Empty array", []int{}, []int{}, 0}, | ||
{"Only duplicates", []int{1, 1, 1, 1}, []int{1}, 1}, | ||
} | ||
|
||
for _, tt := range tests { | ||
t.Run(tt.name, func(t *testing.T) { | ||
result := RemoveDuplicates(tt.input) | ||
if result != tt.output { | ||
t.Errorf("RemoveDuplicates(%v) = %v; want %v", tt.input, result, tt.output) | ||
} | ||
}) | ||
} | ||
} |