forked from freelf/Algorithm21
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTwoSum.swift
More file actions
37 lines (35 loc) · 901 Bytes
/
Copy pathTwoSum.swift
File metadata and controls
37 lines (35 loc) · 901 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
32
33
34
35
36
37
//
// TwoSum.swift
// ConquerAlgorithm
//
// Created by Freelf on 2021/2/5.
// Copyright © 2021 Freelf. All rights reserved.
//
// 1. 两数之和
// https://leetcode-cn.com/problems/two-sum/
import Foundation
class TwoSumSolution {
func twoSum(_ nums: [Int], _ target: Int) -> [Int] {
var dict = [Int : Int]()
for i in 0 ..< nums.count {
let num = nums[i]
let wantFind = target - num
if let find = dict[wantFind] {
return [find, i]
} else {
dict[num] = i
}
}
return []
}
func twoSum2(_ nums: [Int], _ target: Int) -> [Int] {
for i in 0 ..< nums.count {
for j in i + 1 ..< nums.count {
if nums[i] + nums[j] == target {
return [i, j];
}
}
}
return []
}
}