Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Two Sum 不需要多构造出一个 hash 变量啊 #1

Open
OnePieceLv opened this issue Jan 19, 2017 · 4 comments
Open

Two Sum 不需要多构造出一个 hash 变量啊 #1

OnePieceLv opened this issue Jan 19, 2017 · 4 comments

Comments

@OnePieceLv
Copy link

func twoSum(_ nums: [Int], _ target: Int) -> [Int] {
var array = Int
nums.enumerated().forEach { (offset: Int, element: Int)in
if let index = nums.index(where: { (target - element) == $0}) {
array.append(contentsOf: [index,offset])
}
}
return array
}

@OnePieceLv OnePieceLv changed the title Two Sum 不需要多构造出一个 hash 变量啊,swift 写 leetcode 很容易啊 Two Sum 不需要多构造出一个 hash 变量啊 Jan 19, 2017
@OnePieceLv
Copy link
Author

OnePieceLv commented Jan 19, 2017

如果用 $0 来做类型推倒的话,还可以再简洁点。

@DaiYue
Copy link
Owner

DaiYue commented Jan 21, 2017

哈哈,我猜 var array = Intvar array : [Int] = [] 的意思吧?~

不过用上面的代码会导致重复 >< 比如[3,-2,4], 1这个 case 得出来结果是 [1, 0, 0, 1],正确应该是 [1, 0] 或者 [0, 1] 这样。其实 break 一下就好了,不过看文档似乎 foreach 不能 break……

hash 当然不是必须用,不过用 hash 是为了让效率提升的。只是用 array 的查找,每一次循环没法利用到前面的结果。

@OnePieceLv
Copy link
Author

OnePieceLv commented Jan 22, 2017

那个是笔误,var array:[[Int]] = [], 结果应该是 [[1,0],[0,1]]。

@DaiYue
Copy link
Owner

DaiYue commented Jan 22, 2017

如果是 var array:[[Int]] = [] 的话,array.append(contentsOf: [index,offset]) 这句就编不过了。改成了 array.append([index,offset])

另外还有点小问题,比如这个 case :[3,2,4], 6 得出结果包括 [0,0] 实际应该只有 [1,2],一个数是不能用两次的。加上 if index != offset 可以解决。

不过放在 leetcode 上测的时候,第 15 个 case 会超时,可以去 https://leetcode.com/problems/two-sum/ 试一下。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants