美文网首页
LeetCode之Swift

LeetCode之Swift

作者: China_ly | 来源:发表于2017-03-22 10:46 被阅读0次

    1.Two Sum (Easy)

    时间复杂度对O(n^2)
    func twoSum(_ nums: [Int], _ target: Int) -> [Int] {
            for i in 0 ..< nums.count {
                for j in i + 1 ..< nums.count {
                    let result = nums[i] + nums[j]
                    if result == target {
                        return [i, j]
                    }
                }
            }
            return [-1, -1]
        }
    
    时间复杂度O(n)
    func twoSum_3(_ nums: [Int], _ target: Int) -> [Int] {
            var numberIndexDict = [Int:Int]()
            
            for (index, num) in nums.enumerated() {
                guard let pairedIndex = numberIndexDict[target - num] else {
                    numberIndexDict[num] = index
                    continue
                }
                
                return [pairedIndex, index]
            }
            
            return [-1, -1]
        }
    

    相关文章

      网友评论

          本文标题:LeetCode之Swift

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