Skip to content

Commit 74353b8

Browse files
committed
feat: add solution for Two Sum problem on LeetCode
1 parent e042fa3 commit 74353b8

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

two-sum/WhiteHyun.swift

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
//
2+
// 1. Two Sum.swift
3+
// https://leetcode.com/problems/two-sum/description/
4+
// Algorithm
5+
//
6+
// Created by 홍승현 on 2024/04/26.
7+
//
8+
9+
import Foundation
10+
11+
final class LeetCode1 {
12+
func twoSum(_ numbers: [Int], _ target: Int) -> [Int] {
13+
let sortedNumbersWithIndex = numbers.enumerated().sorted { lhs, rhs in
14+
lhs.element < rhs.element
15+
}
16+
var left = 0
17+
var right = sortedNumbersWithIndex.endIndex - 1
18+
19+
while left < right {
20+
let sum = sortedNumbersWithIndex[left].element + sortedNumbersWithIndex[right].element
21+
if sum == target { break }
22+
if sum < target {
23+
left += 1
24+
} else {
25+
right -= 1
26+
}
27+
}
28+
29+
return [sortedNumbersWithIndex[left].offset, sortedNumbersWithIndex[right].offset]
30+
}
31+
}

0 commit comments

Comments
 (0)