Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit cca07b9

Browse files
committedJan 24, 2023
add solution task #15 3Sum
1 parent 82afdcd commit cca07b9

File tree

4 files changed

+86
-0
lines changed

4 files changed

+86
-0
lines changed
 

Diff for: ‎README.md

+1
Original file line numberDiff line numberDiff line change
@@ -263,6 +263,7 @@
263263
<summary>Задачи с Leetcode</summary>
264264

265265
- [X] [1. Two Sum](sprint_leetcode/1)
266+
- [X] [15. 3Sum](sprint_leetcode/15)
266267
- [X] [19. Remove Nth Node From End of List](sprint_leetcode/19)
267268
- [X] [33. Search in Rotated Sorted Array](sprint_leetcode/33)
268269
- [X] [56. Merge Intervals](sprint_leetcode/56)

Diff for: ‎sprint_leetcode/15/README.md

+3
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
# 15. 3Sum
2+
3+
Подробнее о задаче: [Тыц](https://leetcode.com/problems/3sum/description/)

Diff for: ‎sprint_leetcode/15/solution.go

+39
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
package main
2+
3+
import (
4+
"sort"
5+
)
6+
7+
func threeSum(nums []int) [][]int {
8+
var res [][]int
9+
10+
sort.Ints(nums)
11+
12+
for i := 0; i < len(nums)-2; i++ {
13+
if i == 0 || (i > 0 && nums[i] != nums[i-1]) {
14+
low := i + 1
15+
high := len(nums) - 1
16+
sum := 0 - nums[i]
17+
18+
for low < high {
19+
if (nums[low] + nums[high]) == sum {
20+
res = append(res, []int{nums[i], nums[low], nums[high]})
21+
for low < high && nums[low] == nums[low+1] {
22+
low++
23+
}
24+
for low < high && nums[high] == nums[high-1] {
25+
high--
26+
}
27+
low++
28+
high--
29+
} else if nums[low]+nums[high] > sum {
30+
high--
31+
} else {
32+
low++
33+
}
34+
}
35+
}
36+
}
37+
38+
return res
39+
}

Diff for: ‎sprint_leetcode/15/solution_test.go

+43
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
package main
2+
3+
import (
4+
"fmt"
5+
"reflect"
6+
"testing"
7+
)
8+
9+
type TestItemInput struct {
10+
nums []int
11+
}
12+
type TestItem struct {
13+
input TestItemInput
14+
output [][]int
15+
}
16+
17+
func TestTask(t *testing.T) {
18+
for i, v := range generateTasks() {
19+
t.Run(fmt.Sprintf("Test %d", i+1), func(t *testing.T) {
20+
res := threeSum(v.input.nums)
21+
if !reflect.DeepEqual(res, v.output) {
22+
t.Errorf("Wrong test.\nOutput: \n%v \nExpected: \n%v", res, v.output)
23+
}
24+
})
25+
}
26+
}
27+
28+
func generateTasks() []TestItem {
29+
return []TestItem{
30+
{
31+
input: TestItemInput{nums: []int{-1, 0, 1, 2, -1, -4}},
32+
output: [][]int{{-1, -1, 2}, {-1, 0, 1}},
33+
},
34+
{
35+
input: TestItemInput{nums: []int{0, 1, 1}},
36+
output: nil,
37+
},
38+
{
39+
input: TestItemInput{nums: []int{0, 0, 0}},
40+
output: [][]int{{0, 0, 0}},
41+
},
42+
}
43+
}

0 commit comments

Comments
 (0)
Please sign in to comment.