美文网首页程序员
100DaysLeetcode(2)

100DaysLeetcode(2)

作者: 叶孤城___ | 来源:发表于2018-04-08 01:40 被阅读363次

Add Two Numbers

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

Solution

class TwoSum {
  func twoSum(_ nums: [Int], _ target: Int) -> [Int] {
    var dict = [Int: Int]()
    for (index, value) in nums.enumerated() {
      dict[value] = index
    }
    for (currentIndex, value) in nums.enumerated() {
      if let index = dict[target - value], index != currentIndex {
        return [currentIndex, index]
      }
    }
    return []
  }
}

相关文章

  • 100DaysLeetcode(2)

    Add Two Numbers Given an array of integers, return indice...

  • 100DaysLeetcode(3)

    Longest Substring Without Repeating Characters Given a st...

  • 100DaysLeetcode(1)

    Add Two Numbers You are given two non-empty linked lists ...

  • DAY 2(2/2)

    五彩滩声名在外,但是我们去的时候在休整,我们十分不甘心,根据各种攻略告诉我们在景区出口有村民守着问你要不要去五彩滩...

  • 2-2-2

    自由写作群 转化与蜕变 继续刚才的梦的后记 我想梦是用最形象的比喻告诉我内在正在经历着发生着什么,这是潜意识里已经...

  • 2 (2)

    突然想到Jenny ,那个有些神经质的女孩儿。 对我来说,Jenny 给我最深的印象是作家。作为一个作家,她的灵感...

  • 2-2-2 RelativeLayout

    标注:本文为个人整理,仅做自己学习参考使用,请勿转载和转发2018-06-03: 初稿,参考博主coder-pig...

  • 2️⃣0️⃣2️⃣0️⃣🔚🔜2️⃣0️⃣2️⃣1️⃣

    今天风小了,夕阳很平静,但2020年终究是不平静的一年。 不平静的2020年,第一次有了一张小区出入证。不能飞去热...

  • 2-2

    ❤️起步,️️(若起步的右车道前方无车,可以不用转到左车道; 转发了右车道一定要变更车道) 一段车程 ❤️右转,右...

  • < маленький принц > 2-2

    Итак, в первый вечер я уснул на песке в пустыне, где на...

网友评论

    本文标题:100DaysLeetcode(2)

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