forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWhiteHyun.swift
More file actions
31 lines (27 loc) · 759 Bytes
/
WhiteHyun.swift
File metadata and controls
31 lines (27 loc) · 759 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
//
// 1. Two Sum.swift
// https://leetcode.com/problems/two-sum/description/
// Algorithm
//
// Created by 홍승현 on 2024/04/26.
//
import Foundation
final class LeetCode1 {
func twoSum(_ numbers: [Int], _ target: Int) -> [Int] {
let sortedNumbersWithIndex = numbers.enumerated().sorted { lhs, rhs in
lhs.element < rhs.element
}
var left = 0
var right = sortedNumbersWithIndex.endIndex - 1
while left < right {
let sum = sortedNumbersWithIndex[left].element + sortedNumbersWithIndex[right].element
if sum == target { break }
if sum < target {
left += 1
} else {
right -= 1
}
}
return [sortedNumbersWithIndex[left].offset, sortedNumbersWithIndex[right].offset]
}
}