Two Sum

作者: ShayneFcf | 来源:发表于2017-06-18 22:31 被阅读2次

计算数组种两个数的和等于给定的目标数的下标,比如数组[2,3,4],目标数7,则返回[1,2]。(这里假设数组里有且只有一对这样的值存在)

class Solution{

          func twoSum(_ nums:[Int],_ target:Int) -> [Int]{

                  var dic = [Int:Int]() //nums里的值作为key,下标作为值

                 for i in 0..<nums.count {

                       let value = nums[i]

                       if let result = dic[target - value]{ //如果存在这样的值,就说明找到了

                       return [result,i]

                   }

             dic[value] = i

           }

          return []

       }

}

相关文章

网友评论

      本文标题:Two Sum

      本文链接:https://www.haomeiwen.com/subject/sepwqxtx.html