給定一個(gè)整數(shù)數(shù)組 nums 和一個(gè)目標(biāo)值 target,請(qǐng)你在該數(shù)組中找出和為目標(biāo)值的那 兩個(gè) 整數(shù),并返回他們的數(shù)組下標(biāo)。
你可以假設(shè)每種輸入只會(huì)對(duì)應(yīng)一個(gè)答案。但是,你不能重復(fù)利用這個(gè)數(shù)組中同樣的元素。
示例:
給定 nums = [2, 7, 11, 15], target = 9
因?yàn)?nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
自己的解法:思路2層for循環(huán)遍歷數(shù)組,判斷2數(shù)之和是否為目標(biāo)值,是則返回,不是繼續(xù)循環(huán),時(shí)間復(fù)雜度n^2
func twoSum(_ nums: [Int], _ target: Int) -> [Int] {
for i in 0..<nums.count{
for j in i+1..<nums.count{
if nums[i] + nums[j] == target{
return [i,j]
}
}
}
return []
}
查看他人的解法:用一個(gè)map來存已經(jīng)遍歷過的數(shù),用目標(biāo)數(shù)-當(dāng)前遍歷的值來計(jì)算需要的值,再判斷map中是否存在該值,有則返回結(jié)果,沒有將當(dāng)前值存入map中,繼續(xù)遍歷,時(shí)間復(fù)雜度n
func twoSum(_ nums: [Int], _ target: Int) -> [Int] {
/// Make a Hash Table of [NumberInInput: IndexOfNumber]
var map: [Int: Int] = [:]
// Loop through nums
for (index, value) in nums.enumerated() {
/// Calculate the number that would be needed
/// to match the target
let complement = target - value
/// Check if the complement exists in the table
if let pair = map[complement] {
return [pair, index]
}
/// Add the complement to the table
map[nums[index]] = index
}
return []
}
學(xué)到的知識(shí)點(diǎn)
enumerated()
可用于快速遍歷,(index,value)中,index表示數(shù)組的索引,value表示值,而且這個(gè)index其實(shí)是offset,看下面的例子。
let array = ["a", "b", "c", "d", "e"]
let arraySlice = array[2..<5]
arraySlice[2] // => "c"
arraySlice.enumerated().first // => (0, "c")
arraySlice[0] // fatalError