美文网首页
两数之和 swift

两数之和 swift

作者: foolish_hungry | 来源:发表于2020-06-16 09:47 被阅读0次

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

    示例:
    给定 nums = [2, 7, 11, 15], target = 9

    因为 nums[0] + nums[1] = 2 + 7 = 9
    所以返回 [0, 1]

    class Solution {
        static func twoSum(_ nums: [Int], _ target: Int) -> [Int] {
            guard nums.count > 1 else {
                return []
            }
            var newNums = nums
            var indexes: [Int] = []
            for (i,x) in nums.enumerated() {
                newNums = Array(newNums.dropFirst())
                for (j,y) in newNums.enumerated() {
                    if x + y == target {
                        indexes += [i, j + i + 1]
                    }
                }
            }
            return indexes
        }
    }
    
    

    💚 技术交流, 希望能给出更合理的写法

    相关文章

      网友评论

          本文标题:两数之和 swift

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