Algorithm Of Swift -- 1.两数之和

题目描述:

        给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。你能够假设每种输入只会对应一个答案。可是,数组中同一个元素不能使用两遍。数组

示例:
   给定 nums = [2, 7, 11, 15], target = 9,由于 nums[0] + nums[1] = 2 + 7 = 9
   因此返回 [0, 1]
解法1:
func twoSum(_ nums: [Int], _ target: Int) -> [Int] {
    var dirt = [Int: Int]()
    for (i,n) in nums.enumerated() {
        if let index = dirt[target - n]  {
            return [index,i]
        }

        dirt[n] = i
    }

    return []
}
解法2:
func twoSum(_ nums: [Int], _ target: Int) -> [Int] {
    var i = 0
    while i < nums.count {
        let temp = target - nums[i]
        for j in i+1..<nums.count {
            if nums[j] == temp {
                var result : [Int] = []
                result.append(i)
                result.append(j)
                return result
            }
        }
        i += 1
    }
    return []
}
相关文章
相关标签/搜索