Skip to content

Commit 18bebfa

Browse files
committed
two sum solution
1 parent cad1385 commit 18bebfa

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

two-sum/radiantchoi.swift

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
class Solution {
2+
func twoSum(_ nums: [Int], _ target: Int) -> [Int] {
3+
let nums = nums.enumerated().sorted { $0.1 < $1.1 }
4+
5+
for (index, num) in nums {
6+
let newTarget = target - num
7+
8+
var left = 0
9+
var right = nums.count - 1
10+
11+
while left <= right {
12+
let mid = (left + right) / 2
13+
14+
if nums[mid].1 == newTarget && nums[mid].0 != index {
15+
return [index, nums[mid].0]
16+
} else if nums[mid].1 < newTarget {
17+
left = mid + 1
18+
} else {
19+
right = mid - 1
20+
}
21+
}
22+
}
23+
24+
return [0, 1]
25+
}
26+
}

0 commit comments

Comments
 (0)