1. Two Sum

找工作的时候经常被问到算法问题,所以开始在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种方案,除此暂时没有更好的方案。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值