File tree Expand file tree Collapse file tree 1 file changed +25
-5
lines changed Expand file tree Collapse file tree 1 file changed +25
-5
lines changed Original file line number Diff line number Diff line change
1
+ type NumAndIdx struct {
2
+ Num int
3
+ Idx int
4
+ }
5
+
1
6
func twoSum (nums []int , target int ) []int {
2
- for i , ni := range nums {
3
- for j , nj := range nums {
4
- if i != j && ni + nj == target {
5
- return []int {i , j }
6
- }
7
+ numAndIdxs := make ([]NumAndIdx , 0 , len (nums ))
8
+ 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 }
7
27
}
8
28
}
9
29
You can’t perform that action at this time.
0 commit comments