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 []
}
相關文章
相關標籤/搜索