leetCode刷题 两数之和

leetCode刷题 两数之和

两数之和

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

你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素

我自己的解答

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

    var index = 0;
    var lastIndex = 0;
    for i in 0..<nums.count {
        let firstNumber = nums[i]
        for j in i+1..<nums.count {
            let lastNumber = nums[j]
            if (firstNumber+lastNumber == target) {
                index = i;
                lastIndex = j;
                print("\(i) 和\(j)")
                break
            }
        }
    }
    return [index,lastIndex]
}

}

最佳解答Swift

class Solution {
    func twoSum(_ nums: [Int], _ target: Int) -> [Int] {
        var theNums = [Int:Int]();
    for i in 0..<nums.count {
        if let result = theNums[target - nums[i]] {
            return [i, result]
        }
        theNums[nums[i]] = i
    }
    
    return [];
    }
}

记录一下,学习牛批的算法

猜你喜欢

转载自blog.csdn.net/weixin_42779997/article/details/88051983