-
Notifications
You must be signed in to change notification settings - Fork 32
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
3 changed files
with
45 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
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,17 @@ | ||
package day164 | ||
|
||
// FindDuplicate returns the one duplicate value between | ||
// 1 to N. | ||
// Assumes N+1 values are provided. | ||
func FindDuplicate(nums []int) int { | ||
sub := len(nums) - 1 | ||
sum := 0 | ||
for _, n := range nums { | ||
sum += n | ||
for sum > 0 && sub > 0 { | ||
sum -= sub | ||
sub-- | ||
} | ||
} | ||
return sum | ||
} |
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,27 @@ | ||
package day164 | ||
|
||
import "testing" | ||
|
||
var testcases = []struct { | ||
nums []int | ||
dup int | ||
}{ | ||
{[]int{3, 1, 5, 4, 2, 4}, 4}, | ||
} | ||
|
||
func TestFindDuplicate(t *testing.T) { | ||
t.Parallel() | ||
for _, tc := range testcases { | ||
if dup := FindDuplicate(tc.nums); dup != tc.dup { | ||
t.Errorf("Expected %v got %v", tc.dup, dup) | ||
} | ||
} | ||
} | ||
|
||
func BenchmarkFindDuplicate(b *testing.B) { | ||
for i := 0; i < b.N; i++ { | ||
for _, tc := range testcases { | ||
FindDuplicate(tc.nums) | ||
} | ||
} | ||
} |