File tree Expand file tree Collapse file tree 1 file changed +4
-25
lines changed Expand file tree Collapse file tree 1 file changed +4
-25
lines changed Original file line number Diff line number Diff line change 1
- type NumAndIdx struct {
2
- Num int
3
- Idx int
4
- }
5
-
6
1
func twoSum (nums []int , target int ) []int {
7
- numAndIdxs := make ([] NumAndIdx , 0 , len (nums ))
2
+ need := make (map [ int ] int , len (nums ))
8
3
for i , n := range nums {
9
- numAndIdxs = append (numAndIdxs , NumAndIdx {Num : n , Idx : i })
10
- }
11
-
12
- sort .Slice (numAndIdxs , func (i , j int ) bool {
13
- return numAndIdxs [i ].Num < numAndIdxs [j ].Num
14
- })
15
-
16
- ldx , rdx := 0 , len (numAndIdxs )- 1
17
-
18
- for ldx < rdx {
19
- l := numAndIdxs [ldx ]
20
- r := numAndIdxs [rdx ]
21
- if sum := l .Num + r .Num ; sum > target {
22
- rdx --
23
- } else if sum < target {
24
- ldx ++
25
- } else {
26
- return []int {l .Idx , r .Idx }
4
+ if j , ok := need [n ]; ok {
5
+ return []int {i , j }
27
6
}
7
+ need [target - n ] = i
28
8
}
29
-
30
9
return nil
31
10
}
You can’t perform that action at this time.
0 commit comments