diff --git a/remove_duplicates_from_sorted_array_26/README.md b/remove_duplicates_from_sorted_array_26/README.md new file mode 100644 index 0000000..fd02fe4 --- /dev/null +++ b/remove_duplicates_from_sorted_array_26/README.md @@ -0,0 +1,3 @@ +# 26. Remove Duplicates from Sorted Array + +https://leetcode.com/problems/remove-duplicates-from-sorted-array/description/ diff --git a/remove_duplicates_from_sorted_array_26/solution.go b/remove_duplicates_from_sorted_array_26/solution.go new file mode 100644 index 0000000..5c81293 --- /dev/null +++ b/remove_duplicates_from_sorted_array_26/solution.go @@ -0,0 +1,22 @@ +package remove_duplicates_from_sorted_array_26 + +func removeDuplicates(nums []int) int { + i, j, u := 0, 0, 1 + for j < len(nums)-1 { + j = i + for j < len(nums)-1 && nums[i] == nums[j] { + j++ + } + if nums[i] != nums[j] { + u++ + } + + for k := j - 1; k > i; k-- { + nums[k] = nums[j] + } + + i++ + } + + return u +} diff --git a/remove_duplicates_from_sorted_array_26/solution_test.go b/remove_duplicates_from_sorted_array_26/solution_test.go new file mode 100644 index 0000000..617bd27 --- /dev/null +++ b/remove_duplicates_from_sorted_array_26/solution_test.go @@ -0,0 +1,37 @@ +package remove_duplicates_from_sorted_array_26 + +import "testing" + +func Test_removeDuplicates(t *testing.T) { + type args struct { + nums []int + } + tests := []struct { + name string + args args + want int + }{ + { + name: "remove duplicates", + args: args{nums: []int{1, 1, 2}}, + want: 2, + }, + { + name: "remove duplicates", + args: args{nums: []int{1, 1}}, + want: 1, + }, + { + name: "remove duplicates", + args: args{nums: []int{0, 0, 1, 1, 1, 2, 2, 3, 3, 4}}, + want: 5, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := removeDuplicates(tt.args.nums); got != tt.want { + t.Errorf("removeDuplicates() = %v, want %v", got, tt.want) + } + }) + } +}