Algorithm Of Swift -- 1.兩數之和
阿新 • • 發佈:2020-12-09
題目描述:
給定一個整數陣列 nums 和一個目標值 target,請你在該陣列中找出和為目標值的那 兩個 整數,並返回他們的陣列下標。你可以假設每種輸入只會對應一個答案。但是,陣列中同一個元素不能使用兩遍。
示例:
給定 nums = [2, 7, 11, 15], target = 9,因為 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 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 [] }