美文网首页
力扣1 - 两数之和

力扣1 - 两数之和

作者: gaookey | 来源:发表于2020-08-31 14:13 被阅读0次

给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。

示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]

func twoSum(_ nums: [Int], _ target: Int) -> [Int] {
    var map = [Int: Int]()
    for index in 0..<nums.count {
        let complement = target - nums[index]
        if map.keys.contains(complement) {
            if let comIndex = map[complement] {
                return [comIndex, index]
            }
        }
        map[nums[index]] = index
    }
    return []
}

//[2, 4]
twoSum([4, 6, 7, 1, 8], 15)
func twoSum(_ nums: [Int], _ target: Int) -> [Int] {
    var map = [Int: Int]()
    for index in 0..<nums.count {
        map[nums[index]] = index
    }
    for index in 0..<nums.count {
        let complement = target - nums[index]
        if map.keys.contains(complement) && map[complement] != index {
            if let uc = map[complement] {
                return [index, uc]
            }
        }
    }
    return []
}
func twoSum(_ nums: [Int], _ target: Int) -> [Int] {
    for i in 0..<nums.count - 1 {
        for j in (i + 1)..<nums.count {
            if ((nums[i] + nums[j]) == target) {
                return [i, j]
            }
        }
    }
    return []
}

//[2, 4]
twoSum([4, 6, 7, 1, 8], 15)

相关文章

  • 力扣1 - 两数之和

    给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的...

  • 力扣-两数之和

    给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的...

  • [力扣] 1. 两数之和

    链接:https://leetcode-cn.com/problems/two-sum 题目 [简单] 给定一个整...

  • 【力扣】1. 两数之和

    题目 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回...

  • 力扣1. 两数之和

    题目 给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target ...

  • ATRS第1周

    ATRS Algorithm算法题: 两数之和 - 力扣 (LeetCode) ``` function twoS...

  • 面试问到的算法

    快排,冒泡区别,两数之和,反转链表,判断环,数组中重复数组350 力扣 力扣26题

  • 前端算法之哈字典&希表

    一、力扣01两数之和 二、力扣217存在重复元素 三、力扣349两个数组的交集 四、力扣1207独一无二的出现次数...

  • LeetCode 15.三数之和

    1、题目 三数之和 - 力扣(LeetCode) https://leetcode-cn.com/problems...

  • 力扣题库_#1.两数之和

    题目 给定一个整数数组nums和一个目标值target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的...

网友评论

      本文标题:力扣1 - 两数之和

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