找工作的时候经常被问到算法问题,所以开始在LeetCode上刷题,由于最近刚开始学swift3.0,于是决定用swift来实现算法。如果哪里写的不对的,欢迎大家纠正。
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution.
Example:
Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].
UPDATE (2016/2/13):
The return format had been changed to zero-based indices. Please read the above updated description carefully.
1. 首先想到就是暴力搜索,2层for循环,逐一比对:代码如下
class Solution {
func twoSum(_ nums: [Int], _ target: Int) -> [Int] {
var array = [Int]()
for i in 0..<nums.count {
for j in i+1..<nums.count {
if target == nums[i] + nums[j] {
array = [i, j]
return array
}
}
}
return array
}
}
运行时间:
756ms
效率很低,但是可以实现。那么,有什么更好的方法呢?
2. 使用字典,将数字作为key,索引作为value,用1次循环,先判断这个key是不是有值,如果没有就向字典中存入;如果有就查找可以匹配和的key。这里需要判断取到的value和当前的index是不同的,比如[3, 3, 2, 4], target = 6,不判断则会返回[0,0]
class Solution {
func twoSum(_ nums: [Int], _ target: Int) -> [Int] {
var array = [Int]()
let dictionary: NSMutableDictionary = NSMutableDictionary()
for index in 0..<nums.count {
var n: Int? = dictionary.object(forKey: nums[index]) as? Int
if n == nil {
dictionary[nums[index]] = index
}
n = dictionary.object(forKey: target - nums[index]) as? Int
if n != nil && n != index {
array = [n!, index]
return array
}
}
return array
}
}
在Leet上第一种可以运行通过,但是第二种却会报错,错误信息如下:
Could not cast value of type 'Swift.AnyHashable' (0x7f5950269b48) to 'Foundation.NSObject' (0x7f594fe6b4d0).
但是我在playground中是可以运行且返回正确结果的,暂时还没弄清楚原因,如果有知道的大神烦请指点一下
补充:
今天看到two sum 2的问题后,补充一点内容在此:如果允许排序,那么完全可以先排序,把问题转化成two sum 2求解,但是如果不允许排序呢?因为我在面试的过程中曾被问到类似问题,要求就是不允许排序,那么只能采用上述2种方案,除此暂时没有更好的方案。