美文网首页
LeetCode解题-Swift

LeetCode解题-Swift

作者: Mage | 来源:发表于2017-08-23 11:32 被阅读59次

1. Two Sum

func twoSum(_ 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]
}
print(twoSum([1,2,3,4,5],9)) => [3,4]

2. Add Two Numbers

public class ListNode: CustomStringConvertible {
     public var val: Int
     public var next: ListNode?
     public init(_ val: Int) {
         self.val = val
         self.next = nil
     }
    public func add(_ nodeVal: Int) -> ListNode {
        let node = ListNode(nodeVal)
        self.next = node
        return node
    }
    public var description: String {
        return "(val:\(self.val) next:\(self.next == nil ? "nil": String(describing: self.next!)))"
    }
}
class Solution {
    func addTwoNumbers(_ l1: ListNode?, _ l2: ListNode?) -> ListNode? {
        return help(l1, l2, 0)
    }
    func help(_ l1: ListNode?, _ l2: ListNode?,_ carry: Int) -> ListNode? {
        if l1 == nil && l2 == nil {
            if carry > 0 {
                return ListNode(carry)
            }
            return nil
        }
        let sum = (l1?.val ?? 0) + (l2?.val ?? 0) + carry
        let node = ListNode(sum % 10)
        node.next = help(l1?.next, l2?.next, sum / 10)
        return node
    }
}
let solution = Solution()
let l1 = ListNode(1)
let l2 = ListNode(9)
l1.add(9)
var node: ListNode? = solution.addTwoNumbers(l1, l2)
print(node?.description ?? "nil")

3.Longest Substring Without Repeating Characters

    func lengthOfLongestSubstring(_ s: String) -> Int {
        let array = s.characters.map{String.init($0)}
        var sub: [String] = []
        var count = 0
        for str in array {
            if let index = sub.index(of: str) {
                if index == sub.count - 1 {
                    sub = [str]
                }else{
                    sub.removeSubrange(0...index)
                    sub.append(str)
                }
            }else{
                sub.append(str)
            }
            count = count < sub.count ? sub.count : count
        }
        return count
    }

相关文章

网友评论

      本文标题:LeetCode解题-Swift

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