[go: nahoru, domu]

Skip to content

Commit

Permalink
Update 1_TwoSum
Browse files Browse the repository at this point in the history
  • Loading branch information
Wang Xingbin committed Sep 21, 2020
1 parent 2489e84 commit bb8be17
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 10 deletions.
4 changes: 3 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
## Playgrounds
timeline.xctimeline
playground.xcworkspace
playground.xcworkspace
LeetCodePlayground.playground/xcuserdata
.DS_Store
15 changes: 10 additions & 5 deletions Array/001_TwoSum.swift
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@

//
// 1.两数之和
//
// 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
// 你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。
//
// 题目链接:https://leetcode-cn.com/problems/two-sum/
// 标签:数组、哈希表
// 要点:顺序遍历目标数组,利用哈希表(Dictionary)查找元素时间复杂度O(1)的特性,
Expand All @@ -12,17 +16,18 @@
import Foundation

class Solution {
typealias Index = Int
func twoSum(_ nums: [Int], _ target: Int) -> [Int] {
// 利用哈希表(Dictionary)查找元素时间复杂度O(1)的特性
var maybeAddendDictionary = [Int: Int]()
var indexesDictionary = [Int: Index]()

for (index, num) in nums.enumerated() {
// 暂存字典中若存在target - num的键值对,即命中返回
if let lastIndex = maybeAddendDictionary[target - num] {
return [lastIndex, index]
if let pairIndex = indexesDictionary[target - num] {
return [pairIndex, index]
}
// 以『元素值』为Key,『元素索引』为Value暂存
maybeAddendDictionary[num] = index
indexesDictionary[num] = index
}

return []
Expand All @@ -31,4 +36,4 @@ class Solution {

// Tests
let s = Solution()
assert(s.twoSum([2,7,11,15], 9) == [0, 1])
assert(s.twoSum([2,7,11,15], 9) == [0, 1])
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@
//
// 1.两数之和
//
// 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
// 你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。
//
// 题目链接:https://leetcode-cn.com/problems/two-sum/
// 标签:数组、哈希表
// 要点:顺序遍历目标数组,利用哈希表(Dictionary)查找元素时间复杂度O(1)的特性,
Expand All @@ -13,17 +16,18 @@
import Foundation

class Solution {
typealias Index = Int
func twoSum(_ nums: [Int], _ target: Int) -> [Int] {
// 利用哈希表(Dictionary)查找元素时间复杂度O(1)的特性
var maybeAddendDictionary = [Int: Int]()
var indexesDictionary = [Int: Index]()

for (index, num) in nums.enumerated() {
// 暂存字典中若存在target - num的键值对,即命中返回
if let lastIndex = maybeAddendDictionary[target - num] {
return [lastIndex, index]
if let pairIndex = indexesDictionary[target - num] {
return [pairIndex, index]
}
// 以『元素值』为Key,『元素索引』为Value暂存
maybeAddendDictionary[num] = index
indexesDictionary[num] = index
}

return []
Expand Down

0 comments on commit bb8be17

Please sign in to comment.