給定一個整數數組 nums 和一個目標值 target,請你在該數組中找出和爲目標值的那 兩個 整數,並返回他們的數組下標。swift
你能夠假設每種輸入只會對應一個答案。可是,你不能重複利用這個數組中一樣的元素。----來源於leetcode數組
示例:app
給定 nums = [2, 7, 11, 15], target = 9 由於 nums[0] + nums[1] = 2 + 7 = 9 因此返回 [0, 1]
下面咱們針對題目進行不一樣方式解答spa
第一種方式: code
暴力法很簡單,遍歷每一個元素x,並查找是否存在一個值與target - x 相等的目標元素,下面是swift代碼解答,可直接運行blog
class Solution { var nums: [Int] = [1,4,15,16,45,86,9,8,3] let target = 17 var tempArr = [Int]() func twoSum(_ nums: [Int], _ target: Int) ->[Int]{ for i in 0..<nums.count { for j in i+1..<nums.count { if nums[j] == target - nums[i] { tempArr.append(i) tempArr.append(j) } } } return tempArr } }
第二種方式:索引
經過一遍哈希表.在進行迭代並將元素插入到表中的同時,還會回頭查看錶中是否已經存在當前元素所對應的目標元素.若是存在,那說明找到了對應的解,並當即將其返回.leetcode
var nums = [22,44,33,66,3,8,4,99] var target = 88 func twoSum(_ nums: [Int], _target: Int) -> [Int] { var result = [Int]() var container = Set<Int>() for (index, value) in nums.enumerated() { let match = target - value if container.contains(match) { let first = nums.firstIndex(of: match)! result.append(first) result.append(index) break } container.insert(value) } return result } let result:[Int] = twoSum(nums, _target: target) print(result)
題解說明:get
1. 建立Hash Container解決時間複雜度問題io
2. 在Hash Container中查找match匹配,
查找成功,找到value和match的索引index
3.查找失敗,將value1存入Hash Container中
4.繼續遍歷數組.
拓展:Set<Int>() ---爲講解
Set講解:
Set與數組不一樣的是,Set裏面的元素是無序的,而且每一個元素都不能重複.
上面就是兩數之和的題解以及拓展知識Set的講解,但願對你們有所幫助.