File tree Expand file tree Collapse file tree 1 file changed +31
-0
lines changed Expand file tree Collapse file tree 1 file changed +31
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments