-
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
74 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,40 @@ | ||
package day393 | ||
|
||
// LargestRangeBrute returns the largest range of integers | ||
// using brute force. | ||
// Runtime is O(N*K) where K is the length of the longest range. | ||
// Effectively, this is O(N^2). | ||
// Converts the input into a hash set. | ||
func LargestRangeBrute(nums []int) (int, int) { | ||
if n := len(nums); n == 0 { | ||
return 0, 0 | ||
} else if n == 1 { | ||
return nums[0], nums[0] | ||
} | ||
|
||
set := make(map[int]struct{}, len(nums)) | ||
|
||
for _, num := range nums { | ||
set[num] = struct{}{} | ||
} | ||
|
||
var longest, sAns, eAns int | ||
|
||
for start := range set { | ||
count := 1 | ||
ptr := start + 1 | ||
|
||
for _, found := set[ptr]; found; _, found = set[ptr] { | ||
count++ | ||
ptr++ | ||
} | ||
|
||
if count > longest || (count == longest && start < sAns) { | ||
longest = count | ||
sAns = start | ||
eAns = ptr - 1 | ||
} | ||
} | ||
|
||
return sAns, eAns | ||
} |
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,33 @@ | ||
package day393 | ||
|
||
import "testing" | ||
|
||
// nolint | ||
var testcases = []struct { | ||
nums []int | ||
start, end int | ||
}{ | ||
{[]int{9, 6, 1, 3, 8, 10, 12, 11}, 8, 12}, | ||
{[]int{}, 0, 0}, | ||
{nil, 0, 0}, | ||
{[]int{12}, 12, 12}, | ||
{[]int{9, 1, 3, 8, 10, 12, 11, 2, 4, 5}, 1, 5}, | ||
} | ||
|
||
func TestLargestRangeBrute(t *testing.T) { | ||
t.Parallel() | ||
|
||
for _, tc := range testcases { | ||
if s, e := LargestRangeBrute(tc.nums); s != tc.start || e != tc.end { | ||
t.Errorf("Expected (%v,%v), got (%v,%v)", tc.start, tc.end, s, e) | ||
} | ||
} | ||
} | ||
|
||
func BenchmarkLargestRangeBrute(b *testing.B) { | ||
for i := 0; i < b.N; i++ { | ||
for _, tc := range testcases { | ||
LargestRangeBrute(tc.nums) | ||
} | ||
} | ||
} |