兩數(shù)之和
給定一個(gè)整數(shù)數(shù)組 nums 和一個(gè)目標(biāo)值 target,請你在該數(shù)組中找出和為目標(biāo)值的那 兩個(gè) 整數(shù),并返回他們的數(shù)組下標(biāo)。
你可以假設(shè)每種輸入只會對應(yīng)一個(gè)答案。但是,你不能重復(fù)利用這個(gè)數(shù)組中同樣的元素。
示例:
給定 nums = [2, 7, 11, 15], target = 9
因?yàn)?nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
解答:
第一次提交: 超時(shí)了...

681586607307_.pic_hd.jpg
正確解答:
// method 1 : 執(zhí)行用時(shí)56ms
func twoSum(_ nums : [Int] , _ target : Int) -> [Int] {
//var dict = Dictionary<Int,Int>()
var dic = [Int:Int]()
var i = 0
for n in nums { //遍歷數(shù)組將每一項(xiàng)數(shù)組值作為key,對應(yīng)的數(shù)組下標(biāo)作為value添加到字典里
dic[n] = i
i += 1
}
var result = [-1, -1]
var j = 0
for n in nums { //遍歷數(shù)組,直接在上述字典中依次查找key為(target - n)的value,找到此value且與j值不同,即為答案
if dic.keys.contains(target - n) && j != dic[target - n] {
result[0] = j
result[1] = dic[target - n] ?? -1
}
j = j + 1
}
return result
}
let arr = [2, 7, 11, 8]
let result_arr = twoSum(arr, 18)
print(result_arr)
// method 2 : 執(zhí)行用時(shí)616ms
func twoSum2(nums : [Int], target : Int) -> [Int] {
for i in 0..<nums.count-1 {
let nn = nums[i]
for j in i+1..<nums.count {
let mm = nums[j]
if nn + mm == target
{
return [i,j]
}
}
}
return [-1,-1]
}
let arr2 = [2, 7, 11, 8]
let result_arr2 = twoSum2(nums: arr2, target: 15)
print(result_arr2)
// method 3 : 耗時(shí)同方法一,但是消耗內(nèi)存更小一些
func twoSum3 (nums : [Int], target : Int) -> [Int] {
var dict : [Int : Int] = [:]
for (index, value) in nums.enumerated() {
if let dValue = dict[target - value] {
return [dValue, index]
}
dict[value] = index
}
return []
}
let arr3 = [2, 7, 11, 8]
let result_arr3 = twoSum3(nums: arr2, target: 15)
print(result_arr3)
關(guān)于for-in
Swift取消了OC中的C形式的for循環(huán)。只用一種單一的for - in形式來取代
其中關(guān)于下標(biāo)的獲取方式
方式一: 通過enumerate來獲取
let testArr = [9,7,3,8,5,2,1,0,6]
for num in testArr {
print(num)
}
for num in testArr.enumerated() {
print(num.element,num.offset)
}
方式二: 使用元組來方便獲取元素索引
for (n, c) in "Swift".characters.enumerated() {
print("\(n): '\(c)'")
}
/// // Prints "0: 'S'"
/// // Prints "1: 'w'"
/// // Prints "2: 'i'"
/// // Prints "3: 'f'"
/// // Prints "4: 't'"