Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 6b1100b

Browse files
authored
add brute force solution for 0001-two-sum (keep-practicing#85)
* add brute force solution for 0001-two-sum * go fmt
1 parent eec99b0 commit 6b1100b

File tree

5 files changed

+25
-7
lines changed

5 files changed

+25
-7
lines changed

‎go.mod

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,3 @@
11
module leetcode
22

3-
go 1.12
3+
go 1.13

‎src/0001_two_sum/twosum.go

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,3 +32,17 @@ func twoSum(nums []int, target int) []int {
3232
}
3333
return []int{}
3434
}
35+
36+
// brute force
37+
// Time complexity: O(n^2)
38+
// Space complexity: O(1)
39+
func twoSum1(nums []int, target int) []int {
40+
for i, j := range nums {
41+
for k := i + 1; k < len(nums); k++ {
42+
if nums[k]+j == target {
43+
return []int{i, k}
44+
}
45+
}
46+
}
47+
return []int{}
48+
}

‎src/0001_two_sum/twosum_test.go

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -8,11 +8,15 @@ import (
88
func TestTwoSum(t *testing.T) {
99
nums := []int{2, 7, 11, 15}
1010

11-
if res := twoSum(nums, 9); !reflect.DeepEqual(res, []int{0, 1}) {
12-
t.Error("Failed, two sum")
13-
}
11+
funcs := []func([]int, int) []int{twoSum, twoSum1}
12+
13+
for _, testFunc := range funcs {
14+
if res := testFunc(nums, 9); !reflect.DeepEqual(res, []int{0, 1}) {
15+
t.Error("Failed, two sum")
16+
}
1417

15-
if res := twoSum(nums, 6); !reflect.DeepEqual(res, []int{}) {
16-
t.Error("Failed, two sum")
18+
if res := testFunc(nums, 6); !reflect.DeepEqual(res, []int{}) {
19+
t.Error("Failed, two sum")
20+
}
1721
}
1822
}

‎src/0713_subarray_product_less_than_k/spltk_test.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ func TestNumSubArrayProductLessThanK(t *testing.T) {
1212
ks := []int{100, 0, 100}
1313
expected := []int{8, 0, 4}
1414

15-
functions := []func([]int, int)int{
15+
functions := []func([]int, int)int{
1616
numSubArrayProductLessThanK,
1717
numSubArrayProductLessThanK2,
1818
}

‎ut.sh renamed to ‎ut.bash

File renamed without changes.

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /