├── .gitignore ├── leetcode-swift.xcodeproj ├── project.xcworkspace │ ├── contents.xcworkspacedata │ └── xcuserdata │ │ └── Rain.xcuserdatad │ │ └── xcdebugger │ │ └── Expressions.xcexplist └── xcuserdata │ └── Rain.xcuserdatad │ ├── xcschemes │ ├── xcschememanagement.plist │ └── leetcode-swift.xcscheme │ └── xcdebugger │ └── Breakpoints_v2.xcbkptlist ├── leetcode-swift ├── Shared │ ├── main.swift │ ├── TreeNode.swift │ ├── ListNode.swift │ ├── LinkedListHelper.swift │ └── BinaryTreeHelper.swift ├── Template │ ├── template.py │ └── template.swift ├── Easy │ ├── q334-reverse-string.swift │ ├── q024-swap-nodes-in-pairs.swift │ ├── q237-delete-node-in-a-linked-list.swift │ ├── q217-contains-duplicate.swift │ ├── q104-maximum-depth-of-binary-tree.swift │ ├── q070-climbing-stairs.swift │ ├── q237-delete-node-in-a-linked-list.py │ ├── q219-contains-duplicate-ii.swift │ ├── q231-power-of-two.swift │ ├── q118-pascals-triangle.swift │ ├── q349-Intersection-of-two-arrays.swift │ ├── q083-remove-duplicates-from-sorted-list.swift │ ├── q172-factorial-trailing-zeroes.swift │ ├── q258-add-digits.swift │ ├── q263-ugly-number.swift │ ├── q190-reverse-bits.swift │ ├── q191-number-of-1-bits.py │ ├── q066-plus-one.swift │ ├── q119-pascals-triangle-ii.swift │ ├── q326-power-of-three.swift │ ├── q303-range-sum-query-immutable.swift │ ├── q100-same-tree.swift │ ├── q110-balanced-binary-tree.swift │ ├── q191-number-of-1-bits.swift │ ├── q171-excel-sheet-column-number.swift │ ├── q014-longest-common-prefix.swift │ ├── q026-remove-duplicates-from-sorted-array.swift │ ├── q226-invert-binary-tree.swift │ ├── q203-remove-linked-list-elements.swift │ ├── q019-remove-nth-node-from-end-of-list.swift │ ├── q038-count-and-say.swift │ ├── q292-nim-games.swift │ ├── q067-add-binary.swift │ ├── q088-merge-sorted-array.swift │ ├── q141-linked-list-cycle.swift │ ├── q283-move-zeroes.swift │ ├── q009-palindrome-number.swift │ ├── q027-remove-element.swift │ ├── q020-valid-parentheses.swift │ ├── q242-valid-anagram.swift │ ├── q058-length-of-last-word.swift │ ├── q111-minimum-depth-of-binary-tree.swift │ ├── q007-reverse-integer.swift │ ├── q121-best-time-to-buy-and-sell-stock.swift │ ├── q371-sum-of-two-integers.swift │ ├── q257-binary-tree-paths.swift │ ├── q102-binary-tree-level-order-traversal.swift │ ├── q107-binary-tree-level-order-traversal-ii.swift │ ├── q205-isomorphic-strings.swift │ ├── q345-reverse-vowels-of-a-string.swift │ ├── q160-majority-element.swift │ ├── q021-merge-two-sorted-lists.swift │ ├── q342-power-of-four.swift │ ├── q299-bulls-and-cows.swift │ ├── q206-reverse-linked-list.swift │ ├── q202-happy-number.swift │ ├── q290-word-pattern.swift │ ├── q198-house-robber.swift │ ├── q112-path-sum.swift │ ├── q225-implement-stack-using-queues.swift │ ├── q232-implement-queue-using-stacks.swift │ ├── q013-roman-to-integer.swift │ ├── q235-lowest-common-ancestor-of-a-binary-search-tree.py │ ├── q234-palindrome-linked-list.swift │ ├── q223-rectangle-area.swift │ ├── q036-valid-sudoku.swift │ ├── q350-intersection-of-two-arrays-ii.swift │ ├── q160-intersection-of-two-linked-lists.swift │ ├── q028-implement-strstr.swift │ ├── q235-lowest-common-ancestor-of-a-binary-search-tree.swift │ ├── q101-symmetric-tree.swift │ └── q204-count-primes.swift └── Medium │ ├── q122-best-time-to-buy-and-sell-stock-ii.swift │ ├── q213-house-robber-ii.swift │ └── q103-binary-tree-zigzag-level-order-traversal.swift ├── LICENSE └── util ├── generate-solution-symlink.py ├── generate-readme.py └── readme-header.md /.gitignore: -------------------------------------------------------------------------------- 1 | L*.swift -------------------------------------------------------------------------------- /leetcode-swift.xcodeproj/project.xcworkspace/contents.xcworkspacedata: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /leetcode-swift/Shared/main.swift: -------------------------------------------------------------------------------- 1 | // 2 | // main.swift 3 | // leetcode-swift 4 | // 5 | // Created by Tianyu Wang on 16/6/27. 6 | // Github : http://github.com/wty21cn 7 | // Website : http://wty.im 8 | // Linkedin : https://www.linkedin.com/in/wty21cn 9 | // Mail : mailto:wty21cn@gmail.com 10 | 11 | import Foundation 12 | 13 | 14 | q14.getSolution() 15 | -------------------------------------------------------------------------------- /leetcode-swift/Template/template.py: -------------------------------------------------------------------------------- 1 | #! _*_encoding:utf-8_*_ 2 | ''' 3 | .py 4 | leetcode-swift 5 | Source* : 6 | Category* : 7 | 8 | Created by Tianyu Wang on 16/6/29. 9 | Github : http://github.com/wty21cn 10 | Website : http://wty.im 11 | Linkedin : https://www.linkedin.com/in/wty21cn 12 | Mail : mailto:wty21cn@gmail.com 13 | ''' 14 | 15 | 16 | class Solution(object): 17 | 18 | 19 | if __name__ == "__main__": 20 | print(Solution()) -------------------------------------------------------------------------------- /leetcode-swift/Template/template.swift: -------------------------------------------------------------------------------- 1 | // 2 | // template.swift 3 | // leetcode-swift 4 | // Source* : 5 | // Category* : 6 | // 7 | // Created by Tianyu Wang on 16/7/9. 8 | // Github : http://github.com/wty21cn 9 | // Website : http://wty.im 10 | // Linkedin : https://www.linkedin.com/in/wty21cn 11 | // Mail : mailto:wty21cn@gmail.com 12 | 13 | 14 | import Foundation 15 | 16 | struct q { 17 | 18 | class Solution { 19 | } 20 | 21 | static func getSolution() -> Void { 22 | print(Solution()) 23 | } 24 | } -------------------------------------------------------------------------------- /leetcode-swift.xcodeproj/xcuserdata/Rain.xcuserdatad/xcschemes/xcschememanagement.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | SchemeUserState 6 | 7 | leetcode-swift.xcscheme 8 | 9 | orderHint 10 | 0 11 | 12 | 13 | SuppressBuildableAutocreation 14 | 15 | B76B77D61D281C190093657C 16 | 17 | primary 18 | 19 | 20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /leetcode-swift.xcodeproj/xcuserdata/Rain.xcuserdatad/xcdebugger/Breakpoints_v2.xcbkptlist: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | 8 | 20 | 21 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /leetcode-swift.xcodeproj/project.xcworkspace/xcuserdata/Rain.xcuserdatad/xcdebugger/Expressions.xcexplist: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 7 | 8 | 10 | 11 | 12 | 13 | 15 | 16 | 18 | 19 | 21 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2016 Tianyu Wang 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. -------------------------------------------------------------------------------- /leetcode-swift/Shared/TreeNode.swift: -------------------------------------------------------------------------------- 1 | // 2 | // TreeNode.swift 3 | // leetcode-swift 4 | // 5 | // Created by Tianyu Wang on 16/6/29. 6 | // Github : http://github.com/wty21cn 7 | // Website : http://wty.im 8 | // Linkedin : https://www.linkedin.com/in/wty21cn 9 | // Mail : mailto:wty21cn@gmail.com 10 | 11 | import Foundation 12 | 13 | class TreeNode: BinaryTreeNodePrintable, CustomStringConvertible { 14 | var val: Int 15 | var left: TreeNode? 16 | var right: TreeNode? 17 | 18 | init(_ val: Int) { 19 | self.val = val 20 | self.left = nil 21 | self.right = nil 22 | } 23 | 24 | //MARK:- BinaryTreeNodePrintable Protocol 25 | 26 | func leftSubTree() -> BinaryTreeNodePrintable? { 27 | return left 28 | } 29 | 30 | func rightSubTree() -> BinaryTreeNodePrintable? { 31 | return right 32 | } 33 | 34 | func presentation() -> String { 35 | return "\(val)" 36 | } 37 | 38 | //MARK: - CustomStringConvertible Protocol { 39 | 40 | var description: String { 41 | 42 | return BinaryTreeHelper.getStructureDescription(forNode: self) 43 | } 44 | 45 | } -------------------------------------------------------------------------------- /leetcode-swift/Easy/q334-reverse-string.swift: -------------------------------------------------------------------------------- 1 | // 2 | // q334-reverse-string.swift 3 | // leetcode-swift 4 | // Source* : https://leetcode.com/problems/reverse-string/ 5 | // Category* : String 6 | // 7 | // Created by Tianyu Wang on 16/6/27. 8 | // Github : http://github.com/wty21cn 9 | // Website : http://wty.im 10 | // Linkedin : https://www.linkedin.com/in/wty21cn 11 | // Mail : mailto:wty21cn@gmail.com 12 | 13 | 14 | 15 | /*************************************************************************************** 16 | * 17 | * Write a function that takes a string as input and returns the string reversed. 18 | * 19 | * Example: 20 | * Given s = "hello", return "olleh". 21 | * 22 | ***************************************************************************************/ 23 | 24 | 25 | import Foundation 26 | 27 | struct q344 { 28 | 29 | class Solution { 30 | func reverseString(_ s: String) -> String { 31 | return String(s.characters.reversed()) 32 | } 33 | } 34 | 35 | static func getSolution() -> Void { 36 | let solution = Solution() 37 | print(solution.reverseString("123")) 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /leetcode-swift/Shared/ListNode.swift: -------------------------------------------------------------------------------- 1 | // 2 | // ListNode.swift 3 | // leetcode-swift 4 | // 5 | // Created by Tianyu Wang on 16/6/29. 6 | // Github : http://github.com/wty21cn 7 | // Website : http://wty.im 8 | // Linkedin : https://www.linkedin.com/in/wty21cn 9 | // Mail : mailto:wty21cn@gmail.com 10 | 11 | import Foundation 12 | 13 | open class ListNode: ListNodePrintable, CustomStringConvertible { 14 | open var val: Int 15 | open var next: ListNode? 16 | open var length: Int { 17 | if let nextNode = next { 18 | return nextNode.length + 1 19 | } else { 20 | return 1 21 | } 22 | } 23 | 24 | public init(_ val: Int) { 25 | self.val = val 26 | self.next = nil 27 | } 28 | 29 | //MARK: - ListNodePrintable Protocol 30 | 31 | func presentation() -> String { 32 | return "\(val)" 33 | } 34 | 35 | func successor() -> ListNodePrintable? { 36 | return next 37 | } 38 | 39 | //MARK: - CustomStringConvertible Protocol { 40 | 41 | open var description: String { 42 | return LinkedListHelper.getStructureDescription(forNode: self) 43 | } 44 | 45 | } 46 | -------------------------------------------------------------------------------- /leetcode-swift/Easy/q024-swap-nodes-in-pairs.swift: -------------------------------------------------------------------------------- 1 | // 2 | // q024-swap-nodes-in-pairs.swift 3 | // leetcode-swift 4 | // Source* : https://leetcode.com/problems/swap-nodes-in-pairs/ 5 | // Category* : LinkedList TwoPointers 6 | // 7 | // Created by Tianyu Wang on 16/7/1. 8 | // Github : http://github.com/wty21cn 9 | // Website : http://wty.im 10 | // Linkedin : https://www.linkedin.com/in/wty21cn 11 | // Mail : mailto:wty21cn@gmail.com 12 | 13 | 14 | import Foundation 15 | 16 | struct q24 { 17 | 18 | class Solution { 19 | func swapPairs(_ head: ListNode?) -> ListNode? { 20 | 21 | var p: ListNode? = nil 22 | var i = head 23 | var n = head?.next 24 | let head = n != nil ? n : head 25 | 26 | while n != nil { 27 | i!.next = n!.next 28 | n!.next = i 29 | p?.next = n 30 | 31 | p = i 32 | i = i!.next 33 | n = i?.next 34 | } 35 | 36 | return head 37 | 38 | } 39 | } 40 | 41 | static func getSolution() -> Void { 42 | 43 | let head = LinkedListHelper.buildLinkedList(withNodes: [1,2,3,4,5,6,7,8,9]) 44 | 45 | print(Solution().swapPairs(head) ?? "") 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /leetcode-swift/Easy/q237-delete-node-in-a-linked-list.swift: -------------------------------------------------------------------------------- 1 | // 2 | // q237-delete-node-in-a-linked-list.swift 3 | // leetcode-swift 4 | // Source* : https://leetcode.com/problems/delete-node-in-a-linked-list/ 5 | // Category* : LinkedList 6 | // 7 | // Created by Tianyu Wang on 16/7/1. 8 | // Github : http://github.com/wty21cn 9 | // Website : http://wty.im 10 | // Linkedin : https://www.linkedin.com/in/wty21cn 11 | // Mail : mailto:wty21cn@gmail.com 12 | 13 | 14 | /********************************************************************************** 15 | * 16 | * Write a function to delete a node (except the tail) in a singly linked list, given 17 | * only access to that node. 18 | * 19 | * Supposed the linked list is 1 -> 2 -> 3 -> 4 and you are given the third node with 20 | * value 3, the linked list should become 1 -> 2 -> 4 after calling your function. 21 | * 22 | **********************************************************************************/ 23 | 24 | 25 | import Foundation 26 | 27 | struct q237 { 28 | 29 | class Solution { 30 | func deleteNode(_ node: ListNode) -> Void { 31 | if let next = node.next { 32 | node.val = next.val 33 | node.next = next.next 34 | } 35 | } 36 | } 37 | 38 | static func getSolution() -> Void { 39 | print(Solution()) 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /leetcode-swift/Easy/q217-contains-duplicate.swift: -------------------------------------------------------------------------------- 1 | // 2 | // q217-contains-duplicate.swift 3 | // leetcode-swift 4 | // Source* : https://leetcode.com/problems/contains-duplicate/ 5 | // Category* : Hash 6 | // 7 | // Created by Tianyu Wang on 16/6/28. 8 | // Github : http://github.com/wty21cn 9 | // Website : http://wty.im 10 | // Linkedin : https://www.linkedin.com/in/wty21cn 11 | // Mail : mailto:wty21cn@gmail.com 12 | 13 | 14 | /********************************************************************************** 15 | * 16 | * Given an array of integers, find if the array contains any duplicates. 17 | * Your function should return true if any value appears at least twice in the array, 18 | * and it should return false if every element is distinct. 19 | * 20 | **********************************************************************************/ 21 | 22 | 23 | import Foundation 24 | 25 | struct q217 { 26 | 27 | class Solution { 28 | func containsDuplicate(_ nums: [Int]) -> Bool { 29 | 30 | var distinctSet = Set() 31 | for num in nums { 32 | if distinctSet.contains(num) { 33 | return true 34 | } else { 35 | distinctSet.insert(num) 36 | } 37 | } 38 | return false 39 | } 40 | } 41 | 42 | static func getSolution() -> Void { 43 | print(Solution().containsDuplicate([1,2,3,4,1])) 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /leetcode-swift/Easy/q104-maximum-depth-of-binary-tree.swift: -------------------------------------------------------------------------------- 1 | // 2 | // q104-maximum-depth-of-binary-tree.swift 3 | // leetcode-swift 4 | // Source* : https://leetcode.com/problems/maximum-depth-of-binary-tree/ 5 | // Category* : BinaryTree RecursiveAlgorithm 6 | // 7 | // Created by Tianyu Wang on 16/6/27. 8 | // Github : http://github.com/wty21cn 9 | // Website : http://wty.im 10 | // Linkedin : https://www.linkedin.com/in/wty21cn 11 | // Mail : mailto:wty21cn@gmail.com 12 | 13 | /********************************************************************************** 14 | * 15 | * Given a binary tree, find its maximum depth. 16 | * 17 | * The maximum depth is the number of nodes along the longest path from the root node 18 | * down to the farthest leaf node. 19 | * 20 | **********************************************************************************/ 21 | 22 | 23 | import Foundation 24 | 25 | struct q104 { 26 | 27 | class Solution { 28 | func maxDepth(_ root: TreeNode?) -> Int { 29 | if root == nil { 30 | return 0 31 | } else { 32 | return 1 + max(maxDepth(root!.left), maxDepth(root!.right)) 33 | } 34 | } 35 | 36 | } 37 | 38 | static func getSolution() -> Void { 39 | let root = BinaryTreeHelper.buildTree(withNodes: [1,2,3,4,nil,6,7,8,nil,10,nil,nil,nil,14,15]) 40 | 41 | print(root ?? "") 42 | 43 | print(Solution().maxDepth(root)) 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /leetcode-swift/Easy/q070-climbing-stairs.swift: -------------------------------------------------------------------------------- 1 | // 2 | // q070-climbing-stairs.swift 3 | // leetcode-swift 4 | // Source* : https://leetcode.com/problems/climbing-stairs/ 5 | // Category* : DynamicProgramming 6 | // 7 | // Created by Tianyu Wang on 16/6/27. 8 | // Github : http://github.com/wty21cn 9 | // Website : http://wty.im 10 | // Linkedin : https://www.linkedin.com/in/wty21cn 11 | // Mail : mailto:wty21cn@gmail.com 12 | 13 | /********************************************************************************** 14 | * 15 | * You are climbing a stair case. It takes n steps to reach to the top. 16 | * 17 | * Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? 18 | * 19 | **********************************************************************************/ 20 | 21 | /* 22 | 23 | Dynamic Programming: 24 | 25 | f[i] = f[i -1] + f[i - 2] 26 | f[0,1,2] = [0,1,2] 27 | 28 | */ 29 | 30 | 31 | import Foundation 32 | 33 | struct q70 { 34 | 35 | class Solution { 36 | func climbStairs(_ n: Int) -> Int { 37 | 38 | var numOfWays = [0,1,2] 39 | if n < 3 { return numOfWays[n] } 40 | 41 | for i in 3...n { 42 | numOfWays.append(numOfWays[i - 1] + numOfWays[i - 2]) 43 | } 44 | return numOfWays[n] 45 | } 46 | } 47 | 48 | static func getSolution() -> Void { 49 | print(Solution().climbStairs(30)) 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /leetcode-swift/Easy/q237-delete-node-in-a-linked-list.py: -------------------------------------------------------------------------------- 1 | #! _*_encoding:utf-8_*_ 2 | ''' 3 | q237-delete-node-in-a-linked-list.py 4 | leetcode-swift 5 | Source* : https://leetcode.com/problems/delete-node-in-a-linked-list/ 6 | Category* : LinkedList 7 | 8 | Created by Tianyu Wang on 16/6/29. 9 | Github : http://github.com/wty21cn 10 | Website : http://wty.im 11 | Linkedin : https://www.linkedin.com/in/wty21cn 12 | Mail : mailto:wty21cn@gmail.com 13 | ''' 14 | 15 | ''' 16 | /********************************************************************************** 17 | * 18 | * Write a function to delete a node (except the tail) in a singly linked list, given 19 | * only access to that node. 20 | * 21 | * Supposed the linked list is 1 -> 2 -> 3 -> 4 and you are given the third node with 22 | * value 3, the linked list should become 1 -> 2 -> 4 after calling your function. 23 | * 24 | **********************************************************************************/ 25 | ''' 26 | 27 | 28 | class ListNode(object): 29 | def __init__(self, x): 30 | self.val = x 31 | self.next = None 32 | 33 | class Solution(object): 34 | def deleteNode(self, node): 35 | """ 36 | :type node: ListNode 37 | :rtype: void Do not return anything, modify node in-place instead. 38 | """ 39 | if node != None and node.next != None: 40 | node.val = node.next.val 41 | node.next = node.next.next 42 | 43 | 44 | if __name__ == "__main__": 45 | print(Solution()) -------------------------------------------------------------------------------- /leetcode-swift/Easy/q219-contains-duplicate-ii.swift: -------------------------------------------------------------------------------- 1 | // 2 | // q219-contains-duplicate-ii.swift 3 | // leetcode-swift 4 | // Source* : https://leetcode.com/problems/contains-duplicate-ii/ 5 | // Category* : Hash 6 | // 7 | // Created by Tianyu Wang on 16/7/4. 8 | // Github : http://github.com/wty21cn 9 | // Website : http://wty.im 10 | // Linkedin : https://www.linkedin.com/in/wty21cn 11 | // Mail : mailto:wty21cn@gmail.com 12 | 13 | 14 | /********************************************************************************** 15 | * 16 | * Given an array of integers and an integer k, find out whether there there are 17 | * two distinct indices i and j in the array such that nums[i] = nums[j] and 18 | * the difference between i and j is at most k. 19 | * 20 | **********************************************************************************/ 21 | 22 | 23 | import Foundation 24 | 25 | struct q219 { 26 | 27 | class Solution { 28 | 29 | func containsNearbyDuplicate(_ nums: [Int], _ k: Int) -> Bool { 30 | var hash = [Int:Int]() 31 | for i in nums.indices.suffix(from: 0) { 32 | if let index = hash[nums[i]] { 33 | if i - index <= k { 34 | return true 35 | } 36 | } 37 | hash[nums[i]] = i 38 | } 39 | return false 40 | } 41 | } 42 | 43 | static func getSolution() -> Void { 44 | print(Solution().containsNearbyDuplicate([1,0,6,2,3,4,5,0], 2)) 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /leetcode-swift/Easy/q231-power-of-two.swift: -------------------------------------------------------------------------------- 1 | // 2 | // q231-power-of-two.swift 3 | // leetcode-swift 4 | // Source* : https://leetcode.com/problems/power-of-two/ 5 | // Category* : Math BitManipulation 6 | // 7 | // Created by Tianyu Wang on 16/6/29. 8 | // Github : http://github.com/wty21cn 9 | // Website : http://wty.im 10 | // Linkedin : https://www.linkedin.com/in/wty21cn 11 | // Mail : mailto:wty21cn@gmail.com 12 | 13 | 14 | 15 | 16 | 17 | /********************************************************************************** 18 | * 19 | * Given an integer, write a function to determine if it is a power of two. 20 | * 21 | * Credits:Special thanks to @jianchao.li.fighter for adding this problem and creating 22 | * all test cases. 23 | * 24 | * 25 | * 26 | **********************************************************************************/ 27 | 28 | 29 | import Foundation 30 | 31 | struct q231 { 32 | 33 | class Solution { 34 | func isPowerOfTwo(_ n: Int) -> Bool { 35 | 36 | var n = n 37 | if n <= 0 { 38 | return false 39 | } 40 | while n % 2 == 0 { 41 | n /= 2 42 | } 43 | return n == 1 44 | 45 | } 46 | } 47 | 48 | class Solution2 { 49 | func isPowerOfTwo(_ n: Int) -> Bool { 50 | return n > 0 && (n & (n - 1) == 0) 51 | } 52 | } 53 | 54 | static func getSolution() -> Void { 55 | print(Solution2().isPowerOfTwo(8388608)) 56 | } 57 | } 58 | 59 | -------------------------------------------------------------------------------- /leetcode-swift/Easy/q118-pascals-triangle.swift: -------------------------------------------------------------------------------- 1 | // 2 | // q118-pascals-triangle.swift 3 | // leetcode-swift 4 | // Source* : https://leetcode.com/problems/pascals-triangle/ 5 | // Category* : Array Math 6 | // 7 | // Created by Tianyu Wang on 16/7/3. 8 | // Github : http://github.com/wty21cn 9 | // Website : http://wty.im 10 | // Linkedin : https://www.linkedin.com/in/wty21cn 11 | // Mail : mailto:wty21cn@gmail.com 12 | 13 | 14 | /********************************************************************************** 15 | * 16 | * Given numRows, generate the first numRows of Pascal's triangle. 17 | * 18 | * For example, given numRows = 5, 19 | * Return 20 | * 21 | * [ 22 | * [1], 23 | * [1,1], 24 | * [1,2,1], 25 | * [1,3,3,1], 26 | * [1,4,6,4,1] 27 | * ] 28 | * 29 | **********************************************************************************/ 30 | 31 | 32 | import Foundation 33 | 34 | struct q118 { 35 | 36 | class Solution { 37 | func generate(_ numRows: Int) -> [[Int]] { 38 | if numRows == 0 { 39 | return [] 40 | } 41 | var result = [[1]] 42 | for row in 1.. Void { 54 | print(Solution().generate(0)) 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /leetcode-swift/Easy/q349-Intersection-of-two-arrays.swift: -------------------------------------------------------------------------------- 1 | // 2 | // q349-Intersection-of-two-arrays 3 | // leetcode-swift 4 | // Source* : https://leetcode.com/problems/intersection-of-two-arrays/ 5 | // Category* : Hash 6 | // 7 | // Created by Tianyu Wang on 16/6/28. 8 | // Github : http://github.com/wty21cn 9 | // Website : http://wty.im 10 | // Linkedin : https://www.linkedin.com/in/wty21cn 11 | // Mail : mailto:wty21cn@gmail.com 12 | 13 | 14 | /*************************************************************************************** 15 | * 16 | * Given two arrays, write a function to compute their intersection. 17 | * 18 | * Example: 19 | * Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2]. 20 | * 21 | * Note: 22 | * Each element in the result must be unique. 23 | * The result can be in any order. 24 | * 25 | ***************************************************************************************/ 26 | 27 | 28 | import Foundation 29 | 30 | struct q349 { 31 | 32 | class Solution { 33 | func intersection(_ nums1: [Int], _ nums2: [Int]) -> [Int] { 34 | let hashTable1: Set = Set(nums1) 35 | let hashTable2: Set = Set(nums2) 36 | var interSection = [Int]() 37 | for num in hashTable2 { 38 | if hashTable1.contains(num) { 39 | interSection.append(num) 40 | } 41 | } 42 | return interSection 43 | } 44 | } 45 | 46 | static func getSolution() -> Void { 47 | print(Solution().intersection([], [])) 48 | } 49 | 50 | } 51 | -------------------------------------------------------------------------------- /leetcode-swift/Shared/LinkedListHelper.swift: -------------------------------------------------------------------------------- 1 | // 2 | // LinkedListHelper.swift 3 | // leetcode-swift 4 | // 5 | // Created by Tianyu Wang on 16/6/29. 6 | // Github : http://github.com/wty21cn 7 | // Website : http://wty.im 8 | // Linkedin : https://www.linkedin.com/in/wty21cn 9 | // Mail : mailto:wty21cn@gmail.com 10 | 11 | import Foundation 12 | 13 | protocol ListNodePrintable { 14 | func presentation() -> String 15 | func successor() -> ListNodePrintable? 16 | } 17 | 18 | 19 | class LinkedListHelper { 20 | 21 | static func buildLinkedList(withNodes nodes: [Int]) -> ListNode? { 22 | var root: ListNode? 23 | var ln: ListNode? 24 | for node in nodes { 25 | if ln != nil { 26 | ln!.next = ListNode(node) 27 | ln = ln!.next 28 | } else { 29 | ln = ListNode(node) 30 | root = ln 31 | } 32 | } 33 | return root 34 | } 35 | } 36 | 37 | extension LinkedListHelper { 38 | fileprivate static let indent = "-->" 39 | 40 | static func getStructureDescription(forNode node: ListNodePrintable?) -> String { 41 | var description = "" 42 | if var node = node { 43 | while true { 44 | description += node.presentation() 45 | if let n = node.successor() { 46 | description += indent 47 | node = n 48 | } else { 49 | break 50 | } 51 | } 52 | } else { 53 | description = "nil" 54 | } 55 | return description 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /leetcode-swift/Easy/q083-remove-duplicates-from-sorted-list.swift: -------------------------------------------------------------------------------- 1 | // 2 | // q083-remove-duplicates-from-sorted-list.swift 3 | // leetcode-swift 4 | // Source* : https://leetcode.com/problems/remove-duplicates-from-sorted-list/ 5 | // Category* : LinkedList 6 | // 7 | // Created by Tianyu Wang on 16/6/29. 8 | // Github : http://github.com/wty21cn 9 | // Website : http://wty.im 10 | // Linkedin : https://www.linkedin.com/in/wty21cn 11 | // Mail : mailto:wty21cn@gmail.com 12 | 13 | 14 | /********************************************************************************** 15 | * 16 | * Given a sorted linked list, delete all duplicates such that each element appear only once. 17 | * 18 | * For example, 19 | * Given 1->1->2, return 1->2. 20 | * Given 1->1->2->3->3, return 1->2->3. 21 | * 22 | * 23 | **********************************************************************************/ 24 | 25 | 26 | import Foundation 27 | 28 | struct q83 { 29 | 30 | class Solution { 31 | func deleteDuplicates(_ head: ListNode?) -> ListNode? { 32 | if var h = head { 33 | while h.next != nil { 34 | if h.val == h.next!.val { 35 | h.next = h.next!.next 36 | } else { 37 | h = h.next! 38 | } 39 | } 40 | } 41 | 42 | return head 43 | } 44 | } 45 | 46 | static func getSolution() -> Void { 47 | let head = LinkedListHelper.buildLinkedList(withNodes: [1,1,3,4,4,5,5,6,6,7]) 48 | print(head ?? "") 49 | print(Solution().deleteDuplicates(head) ?? "") 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /leetcode-swift/Easy/q172-factorial-trailing-zeroes.swift: -------------------------------------------------------------------------------- 1 | // 2 | // q172-factorial-trailing-zeroes.swift 3 | // leetcode-swift 4 | // Source* : https://leetcode.com/problems/factorial-trailing-zeroes/ 5 | // Category* : Math 6 | // 7 | // Created by Tianyu Wang on 16/7/4. 8 | // Github : http://github.com/wty21cn 9 | // Website : http://wty.im 10 | // Linkedin : https://www.linkedin.com/in/wty21cn 11 | // Mail : mailto:wty21cn@gmail.com 12 | 13 | 14 | /********************************************************************************** 15 | * 16 | * Given an integer n, return the number of trailing zeroes in n!. 17 | * 18 | * Note: Your solution should be in polynomial time complexity. 19 | * 20 | * Credits:Special thanks to @ts for adding this problem and creating all test cases. 21 | * 22 | **********************************************************************************/ 23 | 24 | /* 25 | 26 | 5 * 2 = 10, the trailing zereos comes from this equation 27 | n / 5 can calculate how many five we have from 1 to n 28 | n / 25 = n / (5 * 5), this will give us extra 5 compare to n / 5 29 | n / 125 = n / (5 * 5 * 5), more extra 5 30 | ... 31 | 32 | */ 33 | 34 | 35 | import Foundation 36 | 37 | struct q172 { 38 | 39 | class Solution { 40 | func trailingZeroes(_ n: Int) -> Int { 41 | var numOfZeros = 0 42 | var countNum = 5 43 | while n / countNum >= 1 { 44 | numOfZeros += n / countNum 45 | countNum *= 5 46 | } 47 | return numOfZeros 48 | } 49 | } 50 | 51 | static func getSolution() -> Void { 52 | print(Solution().trailingZeroes(100)) 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /leetcode-swift/Easy/q258-add-digits.swift: -------------------------------------------------------------------------------- 1 | // 2 | // q258-add-digits.swift 3 | // leetcode-swift 4 | // Source* : https://leetcode.com/problems/add-digits/ 5 | // Category* : Math 6 | // 7 | // Created by Tianyu Wang on 16/6/27. 8 | // Github : http://github.com/wty21cn 9 | // Website : http://wty.im 10 | // Linkedin : https://www.linkedin.com/in/wty21cn 11 | // Mail : mailto:wty21cn@gmail.com 12 | 13 | 14 | 15 | /********************************************************************************** 16 | * 17 | * Given a non-negative integer num, repeatedly add all its digits until the result has only one digit. 18 | * 19 | * For example: 20 | * Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it. 21 | * 22 | * Follow up: 23 | * Could you do it without any loop/recursion in O(1) runtime? 24 | * 25 | **********************************************************************************/ 26 | 27 | 28 | import Foundation 29 | 30 | struct q258 { 31 | 32 | class Solution { 33 | func addDigits(_ num: Int) -> Int { 34 | var num = num 35 | while num / 10 != 0 { 36 | var sum = 0 37 | while num / 10 != 0 { 38 | sum += num % 10 39 | num = num / 10 40 | } 41 | num += sum 42 | } 43 | return num 44 | } 45 | } 46 | 47 | class FollowUpSolution { 48 | func addDigits(_ num: Int) -> Int { 49 | return (num - 1) % 9 + 1 50 | } 51 | } 52 | 53 | static func getSolution() -> Void { 54 | print(Solution().addDigits(10)) 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /leetcode-swift/Easy/q263-ugly-number.swift: -------------------------------------------------------------------------------- 1 | // 2 | // q263-ugly-number.swift 3 | // leetcode-swift 4 | // Source* : https://leetcode.com/problems/ugly-number/ 5 | // Category* : Math 6 | // 7 | // Created by Tianyu Wang on 16/6/27. 8 | // Github : http://github.com/wty21cn 9 | // Website : http://wty.im 10 | // Linkedin : https://www.linkedin.com/in/wty21cn 11 | // Mail : mailto:wty21cn@gmail.com 12 | 13 | 14 | 15 | /*************************************************************************************** 16 | * 17 | * Write a program to check whether a given number is an ugly number. 18 | * 19 | * Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. For 20 | * example, 6, 8 are ugly while 14 is not ugly since it includes another prime factor 7. 21 | * 22 | * Note that 1 is typically treated as an ugly number. 23 | * 24 | * Credits:Special thanks to @jianchao.li.fighter for adding this problem and creating 25 | * all test cases. 26 | * 27 | ***************************************************************************************/ 28 | 29 | 30 | import Foundation 31 | 32 | struct q263 { 33 | 34 | class Solution { 35 | func isUgly(_ num: Int) -> Bool { 36 | var num = num 37 | if num == 0 { return false } 38 | if num == 1 { return true } 39 | while (num % 2 == 0) { num /= 2 } 40 | while (num % 3 == 0) { num /= 3 } 41 | while (num % 5 == 0) { num /= 5 } 42 | return num == 1 43 | 44 | } 45 | } 46 | 47 | static func getSolution() -> Void { 48 | print(Solution().isUgly(25)) 49 | print(Solution().isUgly(30)) 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /leetcode-swift/Easy/q190-reverse-bits.swift: -------------------------------------------------------------------------------- 1 | // 2 | // q190-reverse-bits.swift 3 | // leetcode-swift 4 | // Source* : https://leetcode.com/problems/reverse-bits/ 5 | // Category* : BitManipulation Math 6 | // 7 | // Created by Tianyu Wang on 16/7/6. 8 | // Github : http://github.com/wty21cn 9 | // Website : http://wty.im 10 | // Linkedin : https://www.linkedin.com/in/wty21cn 11 | // Mail : mailto:wty21cn@gmail.com 12 | 13 | 14 | /********************************************************************************** 15 | * 16 | * Reverse bits of a given 32 bits unsigned integer. 17 | * 18 | * For example, given input 43261596 (represented in binary as 00000010100101000001111010011100), 19 | * return 964176192 (represented in binary as 00111001011110000010100101000000). 20 | * 21 | * Follow up: 22 | * If this function is called many times, how would you optimize it? 23 | * 24 | * Related problem: Reverse Integer 25 | * 26 | * Credits:Special thanks to @ts for adding this problem and creating all test cases. 27 | * 28 | **********************************************************************************/ 29 | 30 | 31 | import Foundation 32 | 33 | struct q190 { 34 | 35 | class Solution { 36 | func reversedBits(_ n: UInt32) -> UInt32 { 37 | var n: UInt32 = n 38 | var m: UInt32 = 0 39 | var i: UInt32 = 32 40 | while i > 0 && n != 0 { 41 | m = m << 1 + n & 0b1 42 | n = n >> 1 43 | i -= 1 44 | } 45 | m = m << i 46 | return m 47 | } 48 | } 49 | 50 | static func getSolution() -> Void { 51 | print(Solution().reversedBits(3758096391)) 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /leetcode-swift/Easy/q191-number-of-1-bits.py: -------------------------------------------------------------------------------- 1 | #! _*_encoding:utf-8_*_ 2 | ''' 3 | q191-number-of-1-bits.py 4 | leetcode-swift 5 | Source : https://leetcode.com/problems/number-of-1-bits/ 6 | Category* : Math 7 | 8 | Created by Tianyu Wang on 16/6/29. 9 | Github : http://github.com/wty21cn 10 | Website : http://wty.im 11 | Linkedin : https://www.linkedin.com/in/wty21cn 12 | Mail : mailto:wty21cn@gmail.com 13 | ''' 14 | 15 | 16 | ''' 17 | /********************************************************************************** 18 | * 19 | * Write a function that takes an unsigned integer and returns the number of ’1' bits it has 20 | * (also known as the Hamming weight). 21 | * 22 | * For example, the 32-bit integer ’11' has binary representation 00000000000000000000000000001011, 23 | * so the function should return 3. 24 | * 25 | * Credits:Special thanks to @ts for adding this problem and creating all test cases. 26 | * 27 | **********************************************************************************/ 28 | ''' 29 | 30 | ''' 31 | Normal Solution: 32 | while n != 0, see if the right first binary digit is 1 or 0 using n & 0b1, and then do binary right shift to n 33 | 34 | 35 | Fast Solution: 36 | while n != 0, do n & (n - 1) to eliminate the right first binary digit. 37 | Count the times of this process until n == 0 38 | 39 | ''' 40 | 41 | class Solution(object): 42 | def hammingWeight(self, n): 43 | """ 44 | :type n: int 45 | :rtype: int 46 | """ 47 | num = 0 48 | while n != 0: 49 | n &= (n - 1) 50 | num += 1 51 | return num 52 | 53 | if __name__ == "__main__": 54 | print(Solution().hammingWeight(30)) 55 | -------------------------------------------------------------------------------- /leetcode-swift/Easy/q066-plus-one.swift: -------------------------------------------------------------------------------- 1 | // 2 | // q066-plus-one.swift 3 | // leetcode-swift 4 | // Source* : https://leetcode.com/problems/plus-one/ 5 | // Category* : Array 6 | // 7 | // Created by Tianyu Wang on 16/7/1. 8 | // Github : http://github.com/wty21cn 9 | // Website : http://wty.im 10 | // Linkedin : https://www.linkedin.com/in/wty21cn 11 | // Mail : mailto:wty21cn@gmail.com 12 | 13 | 14 | /********************************************************************************** 15 | * 16 | * Given a non-negative number represented as an array of digits, plus one to the number. 17 | * 18 | * The digits are stored such that the most significant digit is at the head of the list. 19 | * 20 | **********************************************************************************/ 21 | 22 | 23 | import Foundation 24 | 25 | struct q66 { 26 | 27 | class Solution { 28 | func plusOne(_ digits: [Int]) -> [Int] { 29 | 30 | var digits = digits 31 | var index = (digits.endIndex - 1) 32 | var adding = 0 33 | digits[index] += 1 34 | 35 | while index >= digits.startIndex { 36 | digits[index] += adding 37 | adding = digits[index] / 10 38 | if adding > 0 { 39 | digits[index] %= 10 40 | } 41 | index = (index - 1) 42 | } 43 | if adding > 0 { 44 | digits.insert(adding, at: 0) 45 | } 46 | return digits 47 | } 48 | } 49 | 50 | static func getSolution() -> Void { 51 | print(Solution().plusOne([1,9])) 52 | print(Solution().plusOne([9,9])) 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /leetcode-swift/Easy/q119-pascals-triangle-ii.swift: -------------------------------------------------------------------------------- 1 | // 2 | // q119-pascals-triangle-ii.swift 3 | // leetcode-swift 4 | // Source* : https://leetcode.com/problems/pascals-triangle-ii/ 5 | // Category* : Array Math 6 | // 7 | // Created by Tianyu Wang on 16/7/1. 8 | // Github : http://github.com/wty21cn 9 | // Website : http://wty.im 10 | // Linkedin : https://www.linkedin.com/in/wty21cn 11 | // Mail : mailto:wty21cn@gmail.com 12 | 13 | 14 | /********************************************************************************** 15 | * 16 | * Given an index k, return the kth row of the Pascal's triangle. 17 | * 18 | * For example, given k = 3, 19 | * Return [1,3,3,1]. 20 | * 21 | * Note: 22 | * Could you optimize your algorithm to use only O(k) extra space? 23 | * 24 | **********************************************************************************/ 25 | 26 | 27 | import Foundation 28 | 29 | struct q119 { 30 | 31 | class Solution { 32 | func c(m: Int, n: Int) -> Int { 33 | var result = 1, i = 1, j = m 34 | while i <= n { 35 | result = result * j / i 36 | i += 1 37 | j -= 1 38 | } 39 | return result 40 | } 41 | func getRow(_ rowIndex: Int) -> [Int] { 42 | var row = [Int]() 43 | for i in 0...rowIndex { 44 | if i <= rowIndex / 2 { 45 | row.append(c(m: rowIndex, n: i)) 46 | } else { 47 | row.append(row[rowIndex - i]) 48 | } 49 | } 50 | return row 51 | } 52 | } 53 | 54 | static func getSolution() -> Void { 55 | print(Solution().getRow(5)) 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /leetcode-swift/Easy/q326-power-of-three.swift: -------------------------------------------------------------------------------- 1 | // 2 | // q326-power-of-three.swift 3 | // leetcode-swift 4 | // Source* : https://leetcode.com/problems/power-of-three/ 5 | // Category* : Math 6 | // 7 | // Created by Tianyu Wang on 16/6/29. 8 | // Github : http://github.com/wty21cn 9 | // Website : http://wty.im 10 | // Linkedin : https://www.linkedin.com/in/wty21cn 11 | // Mail : mailto:wty21cn@gmail.com 12 | 13 | 14 | /*************************************************************************************** 15 | * 16 | * Given an integer, write a function to determine if it is a power of three. 17 | * 18 | * Follow up: 19 | * Could you do it without using any loop / recursion? 20 | * 21 | * Credits:Special thanks to @dietpepsi for adding this problem and creating all test 22 | * cases. 23 | * 24 | ***************************************************************************************/ 25 | 26 | 27 | import Foundation 28 | 29 | struct q326 { 30 | 31 | class Solution { 32 | func isPowerOfThree(_ n: Int) -> Bool { 33 | let m = log10(Double(n))/log10(3.0) 34 | let epsilon = 0.000000000001 35 | return !m.isNaN && !m.isInfinite ? (m + epsilon).truncatingRemainder(dividingBy: 1) < 2 * epsilon : false 36 | } 37 | } 38 | 39 | class Solution2 { 40 | func isPowerOfThree(_ n: Int) -> Bool { 41 | var n = n 42 | if n <= 0 { 43 | return false 44 | } 45 | while n % 3 == 0 { 46 | n /= 3 47 | } 48 | return n == 1 49 | } 50 | } 51 | 52 | static func getSolution() -> Void { 53 | print(Solution().isPowerOfThree(387420489)) 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /leetcode-swift/Easy/q303-range-sum-query-immutable.swift: -------------------------------------------------------------------------------- 1 | // 2 | // q303-range-sum-query-immutable.swift 3 | // leetcode-swift 4 | // Source* : https://leetcode.com/problems/range-sum-query-immutable/ 5 | // Category* : 6 | // 7 | // Created by Tianyu Wang on 16/7/8. 8 | // Github : http://github.com/wty21cn 9 | // Website : http://wty.im 10 | // Linkedin : https://www.linkedin.com/in/wty21cn 11 | // Mail : mailto:wty21cn@gmail.com 12 | 13 | 14 | /*************************************************************************************** 15 | * 16 | * Given an integer array nums, find the sum of the elements between indices i and j 17 | * (i ≤ j), inclusive. 18 | * 19 | * Example: 20 | * Given nums = [-2, 0, 3, -5, 2, -1] 21 | * 22 | * sumRange(0, 2) -> 1 23 | * sumRange(2, 5) -> -1 24 | * sumRange(0, 5) -> -3 25 | * Note: 26 | * You may assume that the array does not change. 27 | * There are many calls to sumRange function. 28 | * 29 | ***************************************************************************************/ 30 | 31 | 32 | import Foundation 33 | 34 | struct q303 { 35 | 36 | class NumArray { 37 | 38 | var sum: [IntMax]! //sum[i] store the first i elements' sum 39 | 40 | init(_ n: [Int]) { 41 | sum = [IntMax](repeating: 0, count: n.count + 1) 42 | for i in 0.. Int { //i, j are indexs start from zero 48 | return sum[j+1] - sum[i] 49 | } 50 | } 51 | 52 | static func getSolution() -> Void { 53 | let nums = NumArray([1,2,3,4,5,6,7,8,9,10]) 54 | print(nums.sumRange(0,1)) 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /leetcode-swift/Easy/q100-same-tree.swift: -------------------------------------------------------------------------------- 1 | // 2 | // q100-same-tree.swift 3 | // leetcode-swift 4 | // Source* : https://leetcode.com/problems/same-tree/ 5 | // Category* : BinaryTree RecursiveAlgorithm 6 | // 7 | // Created by Tianyu Wang on 16/6/28. 8 | // Github : http://github.com/wty21cn 9 | // Website : http://wty.im 10 | // Linkedin : https://www.linkedin.com/in/wty21cn 11 | // Mail : mailto:wty21cn@gmail.com 12 | 13 | 14 | /********************************************************************************** 15 | * 16 | * Given two binary trees, write a function to check if they are equal or not. 17 | * 18 | * Two binary trees are considered equal if they are structurally identical and the nodes have the same value. 19 | * 20 | * 21 | **********************************************************************************/ 22 | 23 | 24 | import Foundation 25 | 26 | struct q100 { 27 | 28 | class Solution { 29 | func isSameTree(_ p: TreeNode?, _ q: TreeNode?) -> Bool { 30 | if p != nil && q != nil { 31 | return p!.val == q!.val && isSameTree(p!.left, q!.left) && isSameTree(p!.right, q!.right) 32 | } else { 33 | return p == nil && q == nil 34 | } 35 | } 36 | } 37 | 38 | static func getSolution() -> Void { 39 | let tree1 = BinaryTreeHelper.buildTree(withNodes: [1,2,3,4,5,6,7,nil,nil,10,11]) 40 | let tree2 = BinaryTreeHelper.buildTree(withNodes: [1,2,3,4,nil,6,7,8,nil,10,11]) 41 | let tree3 = BinaryTreeHelper.buildTree(withNodes: [1,2,3,4,5,6,7,8,9,10,11]) 42 | let tree4 = BinaryTreeHelper.buildTree(withNodes: [1,2,3,4,5,6,7,8,9,10,11]) 43 | 44 | print(Solution().isSameTree(tree1, tree2)) 45 | print(Solution().isSameTree(tree3, tree4)) 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /leetcode-swift/Easy/q110-balanced-binary-tree.swift: -------------------------------------------------------------------------------- 1 | // 2 | // q110-balanced-binary-tree.swift 3 | // leetcode-swift 4 | // Source* : https://leetcode.com/problems/balanced-binary-tree/ 5 | // Category* : BinaryTree DFS 6 | // 7 | // Created by Tianyu Wang on 16/7/4. 8 | // Github : http://github.com/wty21cn 9 | // Website : http://wty.im 10 | // Linkedin : https://www.linkedin.com/in/wty21cn 11 | // Mail : mailto:wty21cn@gmail.com 12 | 13 | 14 | import Foundation 15 | 16 | struct q110 { 17 | 18 | class Solution { 19 | 20 | func isNodeBalanced(_ node: TreeNode?) -> (Bool,Int) { 21 | if let node = node { 22 | let (isLeftBalanced, leftHeight) = isNodeBalanced(node.left) 23 | if !isLeftBalanced { 24 | return (false, 0) 25 | } 26 | 27 | let (isRightBalanced, rightHeight) = isNodeBalanced(node.right) 28 | if !isRightBalanced { 29 | return (false, 0) 30 | } 31 | 32 | if abs(leftHeight - rightHeight) <= 1 { 33 | return (true, max(leftHeight, rightHeight) + 1) 34 | } else { 35 | return (false, 0) 36 | } 37 | 38 | } else { 39 | return (true, 0) 40 | } 41 | 42 | } 43 | 44 | func isBalanced(_ root: TreeNode?) -> Bool { 45 | 46 | return isNodeBalanced(root).0 47 | 48 | } 49 | } 50 | 51 | static func getSolution() -> Void { 52 | let root = BinaryTreeHelper.buildTree(withNodes: [1,2,3,4,5,6,7,8]) 53 | print(root ?? "") 54 | print(Solution().isBalanced(root)) 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /leetcode-swift/Easy/q191-number-of-1-bits.swift: -------------------------------------------------------------------------------- 1 | // 2 | // q191-number-of-1-bits.swift 3 | // leetcode-swift 4 | // Source* : https://leetcode.com/problems/number-of-1-bits/ 5 | // Category* : Math BitManipulation 6 | // 7 | // Created by Tianyu Wang on 16/6/29. 8 | // Github : http://github.com/wty21cn 9 | // Website : http://wty.im 10 | // Linkedin : https://www.linkedin.com/in/wty21cn 11 | // Mail : mailto:wty21cn@gmail.com 12 | 13 | 14 | /********************************************************************************** 15 | * 16 | * Write a function that takes an unsigned integer and returns the number of ’1' bits it has 17 | * (also known as the Hamming weight). 18 | * 19 | * For example, the 32-bit integer ’11' has binary representation 00000000000000000000000000001011, 20 | * so the function should return 3. 21 | * 22 | * Credits:Special thanks to @ts for adding this problem and creating all test cases. 23 | * 24 | **********************************************************************************/ 25 | 26 | /* 27 | 28 | Normal Solution: 29 | while n != 0, see if the right first binary digit is 1 or 0 using n & 0b1, and then do binary right shift to n 30 | 31 | 32 | Fast Solution: 33 | while n != 0, do n & (n - 1) to eliminate the right first binary digit. 34 | Count the times of this process until n == 0 35 | 36 | */ 37 | 38 | import Foundation 39 | 40 | struct q191 { 41 | 42 | class Solution { 43 | func hammingWeight(_ n: UInt32) -> Int { 44 | var num = 0 45 | var n = n 46 | while n != 0 { 47 | n &= (n - 1) 48 | num += 1 49 | } 50 | return num 51 | } 52 | } 53 | 54 | static func getSolution() -> Void { 55 | print(Solution().hammingWeight(31)) 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /leetcode-swift/Easy/q171-excel-sheet-column-number.swift: -------------------------------------------------------------------------------- 1 | // 2 | // q171-excel-sheet-column-number.swift 3 | // leetcode-swift 4 | // Source* : https://leetcode.com/problems/excel-sheet-column-number/ 5 | // Category* : Math 6 | // 7 | // Created by Tianyu Wang on 16/6/28. 8 | // Github : http://github.com/wty21cn 9 | // Website : http://wty.im 10 | // Linkedin : https://www.linkedin.com/in/wty21cn 11 | // Mail : mailto:wty21cn@gmail.com 12 | 13 | /********************************************************************************** 14 | * 15 | * Related to question Excel Sheet Column Title 16 | * Given a column title as appear in an Excel sheet, return its corresponding column number. 17 | * 18 | * For example: 19 | * A -> 1 20 | * B -> 2 21 | * C -> 3 22 | * ... 23 | * Z -> 26 24 | * AA -> 27 25 | * AB -> 28 26 | * 27 | * Credits:Special thanks to @ts for adding this problem and creating all test cases. 28 | * 29 | **********************************************************************************/ 30 | 31 | 32 | import Foundation 33 | 34 | struct q171 { 35 | 36 | class Solution { 37 | func titleToNumber(_ s: String) -> Int { 38 | let scalarOfA = "A".unicodeScalars.first 39 | var columnNumber = 0 40 | for c in s.characters { 41 | let scalar = String(c).unicodeScalars.first 42 | if let _ = scalarOfA, let _ = scalar { 43 | let value = Int(scalar!.value - scalarOfA!.value + 1) 44 | columnNumber = columnNumber * 26 + value 45 | } else { 46 | return 0 47 | } 48 | } 49 | return columnNumber 50 | } 51 | } 52 | 53 | static func getSolution() -> Void { 54 | print(Solution().titleToNumber("AB")) 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /leetcode-swift/Easy/q014-longest-common-prefix.swift: -------------------------------------------------------------------------------- 1 | // 2 | // q014-longest-common-prefix.swift 3 | // leetcode-swift 4 | // Source* : https://leetcode.com/problems/longest-common-prefix/ 5 | // Category* : String 6 | // 7 | // Created by Tianyu Wang on 16/7/7. 8 | // Github : http://github.com/wty21cn 9 | // Website : http://wty.im 10 | // Linkedin : https://www.linkedin.com/in/wty21cn 11 | // Mail : mailto:wty21cn@gmail.com 12 | 13 | 14 | /********************************************************************************** 15 | * 16 | * Write a function to find the longest common prefix string amongst an array of strings. 17 | * 18 | **********************************************************************************/ 19 | 20 | 21 | import Foundation 22 | 23 | struct q14 { 24 | 25 | class Solution { 26 | func longestCommonPrefix(_ strs: [String]) -> String { 27 | var s: String? //Find the shortest string 28 | var length = Int.max //Shortest string's length 29 | 30 | for str in strs { 31 | if str.characters.count < length { 32 | length = str.characters.count 33 | s = str 34 | } 35 | } 36 | 37 | if var s = s { 38 | var endIndex = s.endIndex 39 | for str in strs { 40 | while !s.isEmpty && !str.hasPrefix(s) { 41 | endIndex = s.index(before: endIndex) 42 | s = s.substring(to: endIndex) 43 | } 44 | } 45 | return s 46 | } else { 47 | return "" 48 | } 49 | } 50 | } 51 | 52 | static func getSolution() -> Void { 53 | print(Solution().longestCommonPrefix(["ab","ab","abc","abcd"])) 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /leetcode-swift/Easy/q026-remove-duplicates-from-sorted-array.swift: -------------------------------------------------------------------------------- 1 | // 2 | // q026-remove-duplicates-from-sorted-array.swift 3 | // leetcode-swift 4 | // Source* : https://leetcode.com/problems/remove-duplicates-from-sorted-array/ 5 | // Category* : Array TwoPointers 6 | // 7 | // Created by Tianyu Wang on 16/7/4. 8 | // Github : http://github.com/wty21cn 9 | // Website : http://wty.im 10 | // Linkedin : https://www.linkedin.com/in/wty21cn 11 | // Mail : mailto:wty21cn@gmail.com 12 | 13 | 14 | /********************************************************************************** 15 | * 16 | * Given a sorted array, remove the duplicates in place such that each element appear 17 | * only once and return the new length. 18 | * 19 | * Do not allocate extra space for another array, you must do this in place with constant memory. 20 | * 21 | * For example, 22 | * Given input array A = [1,1,2], 23 | * 24 | * Your function should return length = 2, and A is now [1,2]. 25 | * 26 | **********************************************************************************/ 27 | 28 | 29 | import Foundation 30 | 31 | struct q26 { 32 | 33 | class Solution { 34 | func removeDuplicates(_ nums: inout [Int]) -> Int { 35 | if nums.isEmpty { 36 | return 0 37 | } 38 | 39 | var i = 1, j = 1 40 | while j < nums.endIndex { 41 | if nums[j] != nums[i - 1] { 42 | nums[i] = nums[j] 43 | i += 1 44 | j += 1 45 | } else { 46 | j += 1 47 | } 48 | } 49 | return i 50 | } 51 | } 52 | 53 | static func getSolution() -> Void { 54 | var array = [1,2,2,2,3,3,4,5,5,6,6] 55 | let num = Solution().removeDuplicates(&array) 56 | for i in 0.. TreeNode? { 46 | if let node = root { 47 | _ = invertTree(node.left) 48 | _ = invertTree(node.right) 49 | 50 | (node.left, node.right) = (node.right, node.left) 51 | } 52 | return root 53 | } 54 | } 55 | 56 | static func getSolution() -> Void { 57 | let root = TreeNode(0) 58 | root.left = TreeNode(1) 59 | root.left!.left = TreeNode(2) 60 | root.left!.right = TreeNode(2) 61 | root.left!.right!.right = TreeNode(3) 62 | 63 | print(Solution().invertTree(root) ?? "") 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /leetcode-swift/Easy/q203-remove-linked-list-elements.swift: -------------------------------------------------------------------------------- 1 | // 2 | // q203-remove-linked-list-elements.swift 3 | // leetcode-swift 4 | // Source* : https://leetcode.com/problems/remove-linked-list-elements/ 5 | // Category* : LinkedList 6 | // 7 | // Created by Tianyu Wang on 16/7/6. 8 | // Github : http://github.com/wty21cn 9 | // Website : http://wty.im 10 | // Linkedin : https://www.linkedin.com/in/wty21cn 11 | // Mail : mailto:wty21cn@gmail.com 12 | 13 | 14 | /********************************************************************************** 15 | * 16 | * Remove all elements from a linked list of integers that have value val. 17 | * 18 | * Example 19 | * Given: 1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6, val = 6 20 | * Return: 1 --> 2 --> 3 --> 4 --> 5 21 | * 22 | * Credits:Special thanks to @mithmatt for adding this problem and creating all test cases. 23 | * 24 | **********************************************************************************/ 25 | 26 | 27 | import Foundation 28 | 29 | struct q203 { 30 | 31 | class Solution { 32 | func removeElements(_ head: ListNode?, _ val: Int) -> ListNode? { 33 | let headPtr = ListNode(0) 34 | headPtr.next = head 35 | var node: ListNode? = headPtr 36 | 37 | while node != nil { 38 | if let next = node!.next { 39 | if next.val == val { 40 | node!.next = next.next 41 | } else { 42 | node = node!.next 43 | } 44 | } else { 45 | node = node!.next 46 | } 47 | } 48 | 49 | return headPtr.next 50 | } 51 | } 52 | 53 | static func getSolution() -> Void { 54 | let head = LinkedListHelper.buildLinkedList(withNodes: [1,2,3,1,1,2,1,2,3,1]) 55 | print(head ?? "") 56 | print(Solution().removeElements(head, 1) ?? "") 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /leetcode-swift/Easy/q019-remove-nth-node-from-end-of-list.swift: -------------------------------------------------------------------------------- 1 | // 2 | // q019-remove-nth-node-from-end-of-list.swift 3 | // leetcode-swift 4 | // Source* : https://leetcode.com/problems/remove-nth-node-from-end-of-list/ 5 | // Category* : LinkedList TwoPointers 6 | // 7 | // Created by Tianyu Wang on 16/7/5. 8 | // Github : http://github.com/wty21cn 9 | // Website : http://wty.im 10 | // Linkedin : https://www.linkedin.com/in/wty21cn 11 | // Mail : mailto:wty21cn@gmail.com 12 | 13 | 14 | /********************************************************************************** 15 | * 16 | * Given a linked list, remove the nth node from the end of list and return its head. 17 | * 18 | * For example, 19 | * 20 | * Given linked list: 1->2->3->4->5, and n = 2. 21 | * 22 | * After removing the second node from the end, the linked list becomes 1->2->3->5. 23 | * 24 | * Note: 25 | * Given n will always be valid. 26 | * Try to do this in one pass. 27 | * 28 | **********************************************************************************/ 29 | 30 | 31 | import Foundation 32 | 33 | struct q19 { 34 | 35 | class Solution { 36 | func removeNthFromEnd(_ head: ListNode?, _ n: Int) -> ListNode? { 37 | if head == nil { return nil } 38 | 39 | var fastPtr = head, slowPtr = head 40 | for _ in 1...n { 41 | fastPtr = fastPtr?.next 42 | } 43 | 44 | if fastPtr == nil { return head!.next } 45 | 46 | while fastPtr?.next != nil { 47 | fastPtr = fastPtr!.next 48 | slowPtr = slowPtr!.next 49 | } 50 | 51 | slowPtr!.next = slowPtr!.next!.next 52 | return head 53 | } 54 | } 55 | 56 | static func getSolution() -> Void { 57 | let head = LinkedListHelper.buildLinkedList(withNodes: [1,2,3,4,5,6,7]) 58 | print(Solution().removeNthFromEnd(head, 1) ?? "") 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /leetcode-swift/Easy/q038-count-and-say.swift: -------------------------------------------------------------------------------- 1 | // 2 | // q038-count-and-say.swift 3 | // leetcode-swift 4 | // Source* : https://leetcode.com/problems/count-and-say/ 5 | // Category* : String 6 | // 7 | // Created by Tianyu Wang on 16/7/6. 8 | // Github : http://github.com/wty21cn 9 | // Website : http://wty.im 10 | // Linkedin : https://www.linkedin.com/in/wty21cn 11 | // Mail : mailto:wty21cn@gmail.com 12 | 13 | 14 | /********************************************************************************** 15 | * 16 | * The count-and-say sequence is the sequence of integers beginning as follows: 17 | * 1, 11, 21, 1211, 111221, ... 18 | * 19 | * 1 is read off as "one 1" or 11. 20 | * 11 is read off as "two 1s" or 21. 21 | * 21 is read off as "one 2, then one 1" or 1211. 22 | * 23 | * Given an integer n, generate the nth sequence. 24 | * 25 | * Note: The sequence of integers will be represented as a string. 26 | * 27 | **********************************************************************************/ 28 | 29 | 30 | import Foundation 31 | 32 | struct q38 { 33 | 34 | class Solution { 35 | func countAndSay(_ n: Int) -> String { 36 | var str = "1" 37 | for _ in 1.. Void { 60 | print(Solution().countAndSay(6)) 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /leetcode-swift/Easy/q292-nim-games.swift: -------------------------------------------------------------------------------- 1 | // 2 | // q292-nim-games.swift 3 | // leetcode-swift 4 | // Source* : https://leetcode.com/problems/nim-game/ 5 | // Category* : GameTheory 6 | // 7 | // Created by Tianyu Wang on 16/6/27. 8 | // Github : http://github.com/wty21cn 9 | // Website : http://wty.im 10 | // Linkedin : https://www.linkedin.com/in/wty21cn 11 | // Mail : mailto:wty21cn@gmail.com 12 | 13 | 14 | /*************************************************************************************** 15 | * 16 | * You are playing the following Nim Game with your friend: There is a heap of stones 17 | * on the table, each time one of you take turns to remove 1 to 3 stones. The one who 18 | * removes the last stone will be the winner. You will take the first turn to remove 19 | * the stones. 20 | * 21 | * Both of you are very clever and have optimal strategies for the game. Write a 22 | * function to determine whether you can win the game given the number of stones in the 23 | * heap. 24 | * 25 | * For example, if there are 4 stones in the heap, then you will never win the game: no 26 | * matter 1, 2, or 3 stones you remove, the last stone will always be removed by your 27 | * friend. 28 | * 29 | * If there are 5 stones in the heap, could you figure out a way to remove the stones 30 | * such that you will always be the winner? 31 | * 32 | * Credits:Special thanks to @jianchao.li.fighter for adding this problem and creating 33 | * all test cases. 34 | * 35 | ***************************************************************************************/ 36 | 37 | /* 38 | 39 | 巴什博弈(同余理论) Bash Game 40 | 先取者必须给对方留下(m+1)的倍数个石子,如不能达成,则先取者必输。其中m为每人一次最多取多少个数 41 | 42 | */ 43 | 44 | 45 | import Foundation 46 | 47 | struct q292 { 48 | 49 | class Solution { 50 | let m = 3 51 | func canWinNim(_ n: Int) -> Bool { 52 | return n % (m + 1) != 0 53 | } 54 | } 55 | 56 | static func getSolution() -> Void { 57 | let solution = Solution() 58 | print(solution.canWinNim(4)) 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /leetcode-swift/Easy/q067-add-binary.swift: -------------------------------------------------------------------------------- 1 | // 2 | // q067-add-binary.swift 3 | // leetcode-swift 4 | // Source* : https://leetcode.com/problems/add-binary/ 5 | // Category* : String BitManipulation 6 | // 7 | // Created by Tianyu Wang on 16/7/7. 8 | // Github : http://github.com/wty21cn 9 | // Website : http://wty.im 10 | // Linkedin : https://www.linkedin.com/in/wty21cn 11 | // Mail : mailto:wty21cn@gmail.com 12 | 13 | 14 | /********************************************************************************** 15 | * 16 | * Given two binary strings, return their sum (also a binary string). 17 | * 18 | * For example, 19 | * a = "11" 20 | * b = "1" 21 | * Return "100". 22 | * 23 | **********************************************************************************/ 24 | 25 | 26 | import Foundation 27 | 28 | struct q67 { 29 | 30 | class Solution { 31 | func addBinary(_ a: String, _ b: String) -> String { 32 | 33 | var result = "" 34 | var a = Array(a.characters) 35 | var b = Array(b.characters) 36 | 37 | var indexA = a.count - 1 38 | var indexB = b.count - 1 39 | var carry = 0 40 | while indexA >= 0 || indexB >= 0 { 41 | //a and b may have different length 42 | let bitA = indexA >= 0 ? Int(String(a[indexA]), radix: 2) : 0 43 | let bitB = indexB >= 0 ? Int(String(b[indexB]), radix: 2) : 0 44 | var sum = bitA! + bitB! + carry 45 | carry = sum / 2 46 | sum %= 2 47 | result.insert("\(sum)".characters.first!, at: result.startIndex) 48 | indexA -= 1 49 | indexB -= 1 50 | } 51 | if carry != 0 { 52 | result.insert("\(carry)".characters.first!, at: result.startIndex) 53 | } 54 | return result 55 | } 56 | } 57 | 58 | static func getSolution() -> Void { 59 | print(Solution().addBinary("110", "11")) 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /leetcode-swift/Easy/q088-merge-sorted-array.swift: -------------------------------------------------------------------------------- 1 | // 2 | // q088-merge-sorted-array.swift 3 | // leetcode-swift 4 | // Source* : https://leetcode.com/problems/merge-sorted-array/ 5 | // Category* : Array 6 | // 7 | // Created by Tianyu Wang on 16/7/5. 8 | // Github : http://github.com/wty21cn 9 | // Website : http://wty.im 10 | // Linkedin : https://www.linkedin.com/in/wty21cn 11 | // Mail : mailto:wty21cn@gmail.com 12 | 13 | 14 | /********************************************************************************** 15 | * 16 | * Given two sorted integer arrays A and B, merge B into A as one sorted array. 17 | * 18 | * Note: 19 | * You may assume that A has enough space (size that is greater or equal to m + n) 20 | * to hold additional elements from B. The number of elements initialized in A and B 21 | * are m and n respectively. 22 | * 23 | **********************************************************************************/ 24 | 25 | 26 | import Foundation 27 | 28 | struct q88 { 29 | 30 | class Solution { 31 | func merge(_ nums1: inout [Int], _ m: Int, _ nums2: [Int], _ n: Int) { 32 | var index = m + n - 1 33 | var i1 = m - 1 34 | var i2 = n - 1 35 | 36 | while i1 >= nums1.startIndex && i2 >= nums2.startIndex { 37 | switch nums1[i1] > nums2[i2] { 38 | case true: 39 | nums1[index] = nums1[i1] 40 | index -= 1 41 | i1 -= 1 42 | case false: 43 | nums1[index] = nums2[i2] 44 | index -= 1 45 | i2 -= 1 46 | } 47 | } 48 | while i2 >= nums2.startIndex { 49 | nums1[index] = nums2[i2] 50 | index -= 1 51 | i2 -= 1 52 | } 53 | } 54 | } 55 | 56 | static func getSolution() -> Void { 57 | var nums1 = [1,2,3,0,0,0] 58 | Solution().merge(&nums1, 3, [2,5,6], 3) 59 | print(nums1) 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /leetcode-swift/Easy/q141-linked-list-cycle.swift: -------------------------------------------------------------------------------- 1 | // 2 | // q141-linked-list-cycle.swift 3 | // leetcode-swift 4 | // Source* : https://leetcode.com/problems/linked-list-cycle/ 5 | // Category* : LinkedList 6 | // 7 | // Created by Tianyu Wang on 16/7/1. 8 | // Github : http://github.com/wty21cn 9 | // Website : http://wty.im 10 | // Linkedin : https://www.linkedin.com/in/wty21cn 11 | // Mail : mailto:wty21cn@gmail.com 12 | 13 | 14 | /********************************************************************************** 15 | * 16 | * Given a linked list, determine if it has a cycle in it. 17 | * 18 | * Follow up: 19 | * Can you solve it without using extra space? 20 | * 21 | * 22 | **********************************************************************************/ 23 | 24 | /* 25 | Use Two pointers to travel through this linked list. 26 | 1.fastPtr and slowPtr start from the head 27 | 2.The fastPtr will move two nodes by one step 28 | 3.The slowPtr will move one node by one step 29 | 30 | if this linked list has a cycle, these two pointer will meet again 31 | */ 32 | 33 | import Foundation 34 | 35 | struct q141 { 36 | 37 | class Solution { 38 | func hasCycle(_ head: ListNode?) -> Bool { 39 | 40 | if head == nil { return false } 41 | 42 | var fastPtr = head?.next?.next 43 | var slowPtr = head?.next 44 | 45 | while fastPtr != nil && slowPtr != nil { 46 | if fastPtr === slowPtr { 47 | return true 48 | } else { 49 | fastPtr = fastPtr?.next?.next 50 | slowPtr = slowPtr?.next 51 | } 52 | } 53 | return false 54 | } 55 | } 56 | 57 | static func getSolution() -> Void { 58 | 59 | let head = LinkedListHelper.buildLinkedList(withNodes: [1,2,3,4,5]) 60 | head?.next?.next?.next?.next?.next = head?.next?.next?.next 61 | 62 | print(Solution().hasCycle(head)) 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /leetcode-swift/Easy/q283-move-zeroes.swift: -------------------------------------------------------------------------------- 1 | // 2 | // q283-move-zeroes.swift 3 | // leetcode-swift 4 | // Source* : https://leetcode.com/problems/move-zeroes/ 5 | // Category* : TwoPointers 6 | // 7 | // Created by Tianyu Wang on 16/6/27. 8 | // Github : http://github.com/wty21cn 9 | // Website : http://wty.im 10 | // Linkedin : https://www.linkedin.com/in/wty21cn 11 | // Mail : mailto:wty21cn@gmail.com 12 | 13 | /*************************************************************************************** 14 | * 15 | * Given an array nums, write a function to move all 0's to the end of it while 16 | * maintaining the relative order of the non-zero elements. 17 | * 18 | * For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums should 19 | * be [1, 3, 12, 0, 0]. 20 | * 21 | * Note: 22 | * You must do this in-place without making a copy of the array. 23 | * Minimize the total number of operations. 24 | * 25 | * Credits: 26 | * Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases. 27 | * 28 | ***************************************************************************************/ 29 | 30 | 31 | import Foundation 32 | 33 | struct q283 { 34 | 35 | class Solution { 36 | func moveZeroes(_ nums: inout [Int]) { 37 | if !nums.isEmpty { 38 | var locIndex = nums.startIndex 39 | var numIndex = nums.startIndex 40 | while numIndex != nums.endIndex { 41 | if nums[numIndex] != 0 { 42 | nums[locIndex] = nums[numIndex] 43 | if locIndex != numIndex { 44 | nums[numIndex] = 0 45 | } 46 | locIndex += 1 47 | } 48 | numIndex += 1 49 | } 50 | } 51 | } 52 | } 53 | 54 | static func getSolution() -> Void { 55 | var array: [Int] = [1, 2, 3, 4] 56 | Solution().moveZeroes(&array) 57 | print(array) 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /leetcode-swift/Easy/q009-palindrome-number.swift: -------------------------------------------------------------------------------- 1 | // 2 | // q009-palindrome-number.swift 3 | // leetcode-swift 4 | // Source* : https://leetcode.com/problems/palindrome-number/ 5 | // Category* : Math 6 | // 7 | // Created by Tianyu Wang on 16/7/4. 8 | // Github : http://github.com/wty21cn 9 | // Website : http://wty.im 10 | // Linkedin : https://www.linkedin.com/in/wty21cn 11 | // Mail : mailto:wty21cn@gmail.com 12 | 13 | 14 | /********************************************************************************** 15 | * 16 | * Determine whether an integer is a palindrome. Do this without extra space. 17 | * 18 | * 19 | * Some hints: 20 | * 21 | * Could negative integers be palindromes? (ie, -1) 22 | * 23 | * If you are thinking of converting the integer to string, note the restriction of using extra space. 24 | * 25 | * You could also try reversing an integer. However, if you have solved the problem "Reverse Integer", 26 | * you know that the reversed integer might overflow. How would you handle such case? 27 | * 28 | * There is a more generic way of solving this problem. 29 | * 30 | **********************************************************************************/ 31 | 32 | 33 | import Foundation 34 | 35 | struct q9 { 36 | 37 | class Solution { 38 | func isPalindrome(_ x: Int) -> Bool { 39 | if x < 0 || x % 10 == 0 { 40 | return x == 0 41 | } 42 | var x = x 43 | var halfReversedX = 0 44 | while x > halfReversedX { 45 | halfReversedX = halfReversedX * 10 + x % 10 46 | x /= 10 47 | } 48 | // even num of digits situation || odd num of digits situaition 49 | return x == halfReversedX || x == halfReversedX / 10 50 | } 51 | } 52 | 53 | static func getSolution() -> Void { 54 | print(Solution().isPalindrome(12344321)) 55 | print(Solution().isPalindrome(123421)) 56 | print(Solution().isPalindrome(0)) 57 | print(Solution().isPalindrome(10)) 58 | 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /leetcode-swift/Easy/q027-remove-element.swift: -------------------------------------------------------------------------------- 1 | // 2 | // q027-remove-element.swift 3 | // leetcode-swift 4 | // Source* : https://leetcode.com/problems/remove-element/ 5 | // Category* : Array TwoPointers 6 | // 7 | // Created by Tianyu Wang on 16/7/3. 8 | // Github : http://github.com/wty21cn 9 | // Website : http://wty.im 10 | // Linkedin : https://www.linkedin.com/in/wty21cn 11 | // Mail : mailto:wty21cn@gmail.com 12 | 13 | 14 | /********************************************************************************** 15 | * 16 | * Given an array and a value, remove all instances of that value in place and return the new length. 17 | * 18 | * The order of elements can be changed. It doesn't matter what you leave beyond the new length. 19 | * 20 | **********************************************************************************/ 21 | 22 | 23 | import Foundation 24 | 25 | struct q27 { 26 | 27 | class Solution { 28 | func removeElement(_ nums: inout [Int], _ val: Int) -> Int { 29 | var checkIndex = nums.startIndex 30 | var contentIndex = nums.startIndex 31 | while checkIndex < nums.endIndex { 32 | if nums[checkIndex] != val { 33 | nums[contentIndex] = nums[checkIndex] 34 | contentIndex += 1 35 | } 36 | checkIndex += 1 37 | } 38 | return contentIndex 39 | } 40 | } 41 | 42 | class Solution2 { 43 | func removeElement(_ nums: inout [Int], _ val: Int) -> Int { 44 | var lastIndex = (nums.endIndex - 1) 45 | var checkIndex = nums.startIndex 46 | while checkIndex <= lastIndex { 47 | if nums[checkIndex] == val { 48 | nums[checkIndex] = nums[lastIndex] 49 | lastIndex -= 1 50 | } else { 51 | checkIndex += 1 52 | } 53 | } 54 | return lastIndex + 1 55 | } 56 | } 57 | 58 | static func getSolution() -> Void { 59 | var nums = [1] 60 | print(Solution2().removeElement(&nums, 3)) 61 | print(nums) 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /leetcode-swift/Easy/q020-valid-parentheses.swift: -------------------------------------------------------------------------------- 1 | // 2 | // q020-valid-parentheses.swift 3 | // leetcode-swift 4 | // Source* : https://leetcode.com/problems/valid-parentheses/ 5 | // Category* : Stack 6 | // 7 | // Created by Tianyu Wang on 16/7/5. 8 | // Github : http://github.com/wty21cn 9 | // Website : http://wty.im 10 | // Linkedin : https://www.linkedin.com/in/wty21cn 11 | // Mail : mailto:wty21cn@gmail.com 12 | 13 | 14 | /********************************************************************************** 15 | * 16 | * Given a string containing just the characters '(', ')', '{', '}', '[' and ']', 17 | * determine if the input string is valid. 18 | * 19 | * The brackets must close in the correct order, "()" and "()[]{}" are all valid 20 | * but "(]" and "([)]" are not. 21 | * 22 | **********************************************************************************/ 23 | 24 | 25 | import Foundation 26 | 27 | struct q20 { 28 | 29 | class Solution { 30 | func isValid(_ s: String) -> Bool { 31 | let rule = Array("()[]{}".characters) 32 | var stack = [Character]() 33 | for (_, char) in s.characters.enumerated() { 34 | if rule.index(of: char)! % 2 == 0 { // open brackets 35 | stack.append(char) 36 | } else { // close brackets 37 | if stack.isEmpty { 38 | return false 39 | } else { 40 | if rule.index(of: char)! - rule.index(of: stack.last!)! == 1 { //barckets matched 41 | stack.removeLast() 42 | } else { 43 | return false 44 | } 45 | } 46 | } 47 | } 48 | return stack.isEmpty 49 | } 50 | } 51 | 52 | static func getSolution() -> Void { 53 | print(Solution().isValid("((")) 54 | print(Solution().isValid("(])")) 55 | print(Solution().isValid("([{}])")) 56 | print(Solution().isValid("()[]{}")) 57 | print(Solution().isValid("([{)]}")) 58 | 59 | 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /leetcode-swift/Easy/q242-valid-anagram.swift: -------------------------------------------------------------------------------- 1 | // 2 | // q242-valid-anagram.swift 3 | // leetcode-swift 4 | // Source* : https://leetcode.com/problems/valid-anagram/ 5 | // Category* : String Hash 6 | // 7 | // Created by Tianyu Wang on 16/6/28. 8 | // Github : http://github.com/wty21cn 9 | // Website : http://wty.im 10 | // Linkedin : https://www.linkedin.com/in/wty21cn 11 | // Mail : mailto:wty21cn@gmail.com 12 | 13 | 14 | 15 | /********************************************************************************** 16 | * 17 | * Given two strings s and t, write a function to determine if t is an anagram of s. 18 | * 19 | * For example, 20 | * s = "anagram", t = "nagaram", return true. 21 | * s = "rat", t = "car", return false. 22 | * 23 | * Note: 24 | * You may assume the string contains only lowercase alphabets. 25 | * 26 | **********************************************************************************/ 27 | 28 | 29 | import Foundation 30 | 31 | struct q242 { 32 | 33 | class Solution { 34 | func isAnagram(_ s: String, _ t: String) -> Bool { 35 | let charCountS = countCharacter(s) 36 | let charCountT = countCharacter(t) 37 | if s.characters.count != t.characters.count { 38 | return false 39 | } 40 | for (key, value) in charCountS { 41 | if let count = charCountT[key] { 42 | if count == value { 43 | continue 44 | } 45 | } 46 | return false 47 | } 48 | return true 49 | } 50 | 51 | func countCharacter(_ s: String) -> [Character:Int] { 52 | var charCount = [Character:Int]() 53 | for character in s.characters { 54 | if let _ = charCount[character] { 55 | charCount[character]! += 1 56 | } else { 57 | charCount[character] = 1 58 | } 59 | } 60 | return charCount 61 | } 62 | } 63 | 64 | static func getSolution() -> Void { 65 | print(Solution().isAnagram("1233214", "3211233")) 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /leetcode-swift/Easy/q058-length-of-last-word.swift: -------------------------------------------------------------------------------- 1 | // 2 | // q058-length-of-last-word.swift 3 | // leetcode-swift 4 | // Source* : https://leetcode.com/subscribe/ 5 | // Category* : String 6 | // 7 | // Created by Tianyu Wang on 16/7/6. 8 | // Github : http://github.com/wty21cn 9 | // Website : http://wty.im 10 | // Linkedin : https://www.linkedin.com/in/wty21cn 11 | // Mail : mailto:wty21cn@gmail.com 12 | 13 | 14 | /********************************************************************************** 15 | * 16 | * Given a string s consists of upper/lower-case alphabets and empty space characters ' ', 17 | * return the length of last word in the string. 18 | * 19 | * If the last word does not exist, return 0. 20 | * 21 | * Note: A word is defined as a character sequence consists of non-space characters only. 22 | * 23 | * For example, 24 | * Given s = "Hello World", 25 | * return 5. 26 | * 27 | **********************************************************************************/ 28 | 29 | 30 | import Foundation 31 | 32 | struct q58 { 33 | 34 | class Solution { 35 | func lengthOfLastWord(_ s: String) -> Int { 36 | if let lastWord = s.components(separatedBy: " ").filter({ $0 != "" }).last { 37 | return lastWord.characters.count 38 | } else { 39 | return 0 40 | } 41 | } 42 | } 43 | 44 | class Solution2 { 45 | func lengthOfLastWord(_ s: String) -> Int { 46 | if s.isEmpty { 47 | return 0 48 | } 49 | let s = Array(s.characters) 50 | var length = s.count 51 | var lastWordLength = 0 52 | 53 | //trim 54 | while length > 0 && s[length - 1] == " " { 55 | length -= 1 56 | } 57 | 58 | while length > 0 && s[length - 1] != " " { 59 | lastWordLength += 1 60 | length -= 1 61 | } 62 | 63 | return lastWordLength 64 | } 65 | } 66 | 67 | static func getSolution() -> Void { 68 | print(Solution2().lengthOfLastWord(" abcdefgh abcdefg ")) 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /leetcode-swift/Easy/q111-minimum-depth-of-binary-tree.swift: -------------------------------------------------------------------------------- 1 | // 2 | // q111-minimum-depth-of-binary-tree.swift 3 | // leetcode-swift 4 | // Source* : https://leetcode.com/problems/minimum-depth-of-binary-tree/ 5 | // Category* : BinaryTree BFS 6 | // 7 | // Created by Tianyu Wang on 16/7/1. 8 | // Github : http://github.com/wty21cn 9 | // Website : http://wty.im 10 | // Linkedin : https://www.linkedin.com/in/wty21cn 11 | // Mail : mailto:wty21cn@gmail.com 12 | 13 | 14 | /********************************************************************************** 15 | * 16 | * Given a binary tree, find its minimum depth. 17 | * 18 | * The minimum depth is the number of nodes along the shortest path from the root node 19 | * down to the nearest leaf node. 20 | * 21 | **********************************************************************************/ 22 | 23 | 24 | import Foundation 25 | 26 | struct q111 { 27 | 28 | class Solution { 29 | func minDepth(_ root: TreeNode?) -> Int { 30 | if let root = root 31 | { 32 | var queue: [(TreeNode,Int)] = [(root,1)] 33 | var head = queue.startIndex, tail = queue.endIndex 34 | while head < tail { 35 | 36 | let (node, height) = queue[head] 37 | var isLeaf = true 38 | if let l = node.left { 39 | isLeaf = false 40 | queue.append((l, height + 1)) 41 | } 42 | if let r = node.right { 43 | isLeaf = false 44 | queue.append((r, height + 1)) 45 | } 46 | if isLeaf { 47 | return height 48 | } 49 | tail = queue.endIndex 50 | head = (head + 1) 51 | } 52 | 53 | } 54 | return 0 55 | } 56 | } 57 | 58 | static func getSolution() -> Void { 59 | let root = BinaryTreeHelper.buildTree(withNodes: [3,9,20,nil,nil,15,7]) 60 | print(root ?? "") 61 | 62 | print(Solution().minDepth(root)) 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /leetcode-swift/Easy/q007-reverse-integer.swift: -------------------------------------------------------------------------------- 1 | // 2 | // q7-reverse-integer.swift 3 | // leetcode-swift 4 | // Source* : https://leetcode.com/problems/reverse-integer/ 5 | // Category* : Math 6 | // 7 | // Created by Tianyu Wang on 16/7/4. 8 | // Github : http://github.com/wty21cn 9 | // Website : http://wty.im 10 | // Linkedin : https://www.linkedin.com/in/wty21cn 11 | // Mail : mailto:wty21cn@gmail.com 12 | 13 | 14 | /********************************************************************************** 15 | * 16 | * Reverse digits of an integer. 17 | * 18 | * Example1: x = 123, return 321 19 | * Example2: x = -123, return -321 20 | * 21 | * 22 | * Have you thought about this? 23 | * 24 | * Here are some good questions to ask before coding. Bonus points for you if you have already thought through this! 25 | * 26 | * > If the integer's last digit is 0, what should the output be? ie, cases such as 10, 100. 27 | * 28 | * > Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, 29 | * then the reverse of 1000000003 overflows. How should you handle such cases? 30 | * 31 | * > Throw an exception? Good, but what if throwing an exception is not an option? 32 | * You would then have to re-design the function (ie, add an extra parameter). 33 | * 34 | **********************************************************************************/ 35 | 36 | 37 | import Foundation 38 | 39 | struct q007 { 40 | 41 | class Solution { 42 | func reverse(_ x: Int) -> Int { 43 | var x = x 44 | var reversedX = 0 45 | while x != 0 { 46 | reversedX = reversedX * 10 + x % 10 47 | x /= 10 48 | if (reversedX < 0 && x != 0 && Int(Int32.min) / 10 > reversedX ) { return 0 } 49 | if (reversedX > 0 && x != 0 && Int(Int32.max) / 10 < reversedX ) { return 0 } 50 | } 51 | return reversedX 52 | } 53 | } 54 | 55 | static func getSolution() -> Void { 56 | print(Solution().reverse(1534236469)) 57 | print(Solution().reverse(-9223372036854774999)) 58 | print(Solution().reverse(9223372036854774999)) 59 | print(Solution().reverse(-2147483412)) 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /leetcode-swift/Easy/q121-best-time-to-buy-and-sell-stock.swift: -------------------------------------------------------------------------------- 1 | // 2 | // q121-best-time-to-buy-and-sell-stock.swift 3 | // leetcode-swift 4 | // Source* : https://leetcode.com/problems/best-time-to-buy-and-sell-stock/ 5 | // Category* : DynamicProgramming 6 | // 7 | // Created by Tianyu Wang on 16/6/30. 8 | // Github : http://github.com/wty21cn 9 | // Website : http://wty.im 10 | // Linkedin : https://www.linkedin.com/in/wty21cn 11 | // Mail : mailto:wty21cn@gmail.com 12 | 13 | 14 | /********************************************************************************** 15 | * 16 | * Say you have an array for which the ith element is the price of a given stock on day i. 17 | * 18 | * If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), 19 | * design an algorithm to find the maximum profit. 20 | * 21 | **********************************************************************************/ 22 | 23 | /* 24 | Dynamic Programming 25 | 26 | you should remenber the minimum buying price(minBuyingPrice) before day i, and the maximum profit(maxProfit) you can get if you do nothing on day i. 27 | 28 | when considering the max profit you can get on day i, you can choose the following two options 29 | 30 | 1.You can sell the stock, for the best, you can get prices[i] - minBuyingPrice 31 | 2.You can do nothing, so you can get the privious maxProfit 32 | 33 | you should choose max(maxProfit, price - minBuyingPrice) 34 | 35 | when considering the days after day i, you should judge that whether day i is best day for buying stock by judging min(minBuyingPrice, price) 36 | 37 | */ 38 | 39 | 40 | import Foundation 41 | 42 | struct q121 { 43 | 44 | class Solution { 45 | func maxProfit(_ prices: [Int]) -> Int { 46 | 47 | var minBuyingPrice = Int.max 48 | var maxProfit = 0 49 | for price in prices { 50 | maxProfit = max(maxProfit, price - minBuyingPrice) 51 | minBuyingPrice = min(minBuyingPrice, price) 52 | } 53 | return maxProfit 54 | } 55 | } 56 | 57 | static func getSolution() -> Void { 58 | print(Solution().maxProfit([7,6,5,4,3,2,1])) 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /leetcode-swift/Easy/q371-sum-of-two-integers.swift: -------------------------------------------------------------------------------- 1 | // 2 | // q371-sum-of-two-integers.swift 3 | // leetcode-swift 4 | // Source* : https://leetcode.com/problems/sum-of-two-integers/ 5 | // Category* : BitManipulation 6 | // 7 | // Created by Tianyu Wang on 16/7/1. 8 | // Github : http://github.com/wty21cn 9 | // Website : http://wty.im 10 | // Linkedin : https://www.linkedin.com/in/wty21cn 11 | // Mail : mailto:wty21cn@gmail.com 12 | 13 | 14 | 15 | /****************************************************************************************************** 16 | * 17 | * Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -. 18 | * 19 | * Example: 20 | * Given a = 1 and b = 2, return 3. 21 | * 22 | * Credits: 23 | * Special thanks to @fujiaozhu for adding this problem and creating all test cases. 24 | * 25 | ******************************************************************************************************/ 26 | 27 | /* 28 | 29 | For bit by by manipulation addition, without considering the adding, there are four cases 30 | 31 | 0+0=0 32 | 0+1=1 33 | 1+0=1 34 | 1+1=0 35 | 36 | so you can get the result digit at their original position using XOR (^) 37 | 38 | Then let's deal with adding, also four cases 39 | 40 | 0+0=0 x 41 | 0+1=1 x > no adding 42 | 1+0=1 x 43 | 1+1=0 -> has adding 44 | 45 | you can get the adding generatee by the addtion at each position using AND (&) 46 | 47 | Consider the position of each digit is "ABC", so the adding generated by addition on position C will be added to position B, it is the same for position B and A. 48 | 49 | you can get the final adding for this round by using left shift (<<) 50 | 51 | */ 52 | 53 | 54 | import Foundation 55 | 56 | struct q371 { 57 | 58 | class Solution { 59 | func getSum(_ a: Int, _ b: Int) -> Int { 60 | 61 | var sum = a 62 | var carry = b 63 | while carry != 0 { 64 | let t = sum ^ carry 65 | carry = (sum & carry) << 1 66 | sum = t 67 | } 68 | return sum 69 | 70 | } 71 | } 72 | 73 | static func getSolution() -> Void { 74 | print(Solution().getSum(-1203940,1230912848102)) 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /leetcode-swift/Easy/q257-binary-tree-paths.swift: -------------------------------------------------------------------------------- 1 | // 2 | // q257-binary-tree-paths.swift 3 | // leetcode-swift 4 | // Source* : https://leetcode.com/problems/binary-tree-paths/ 5 | // Category* : BinaryTree DFS 6 | // 7 | // Created by Tianyu Wang on 16/7/6. 8 | // Github : http://github.com/wty21cn 9 | // Website : http://wty.im 10 | // Linkedin : https://www.linkedin.com/in/wty21cn 11 | // Mail : mailto:wty21cn@gmail.com 12 | 13 | 14 | /*************************************************************************************** 15 | * 16 | * Given a binary tree, return all root-to-leaf paths. 17 | * 18 | * For example, given the following binary tree: 19 | * 20 | * 1 21 | * / \ 22 | * 2 3 23 | * \ 24 | * 5 25 | * 26 | * All root-to-leaf paths are: 27 | * ["1->2->5", "1->3"] 28 | * 29 | * Credits: 30 | * Special thanks to @jianchao.li.fighter for adding this problem and creating all test 31 | * cases. 32 | * 33 | ***************************************************************************************/ 34 | 35 | 36 | import Foundation 37 | 38 | struct q257 { 39 | 40 | class Solution { 41 | var treePaths = [String]() 42 | 43 | func DFS(node: TreeNode?, path: String) -> Void { 44 | 45 | if let node = node { 46 | 47 | if node.left == nil && node.right != nil { 48 | treePaths.append(path + "->\(node.val)") 49 | } else { 50 | if node.left != nil { 51 | DFS(node: node.left, path: path + "->\(node.val)") 52 | } 53 | if node.right != nil { 54 | DFS(node: node.right, path: path + "->\(node.val)") 55 | } 56 | } 57 | } 58 | } 59 | 60 | func binaryTreePaths(_ root: TreeNode?) -> [String] { 61 | if let root = root { 62 | DFS(node: root, path: "\(root.val)") 63 | } 64 | return treePaths 65 | } 66 | } 67 | 68 | static func getSolution() -> Void { 69 | 70 | let root = BinaryTreeHelper.buildTree(withNodes: [1,2,3,4,5,6,7,8,9,10]) 71 | 72 | print(root ?? "") 73 | print(Solution().binaryTreePaths(root)) 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /leetcode-swift/Easy/q102-binary-tree-level-order-traversal.swift: -------------------------------------------------------------------------------- 1 | // 2 | // q102-binary-tree-level-order-traversal.swift 3 | // leetcode-swift 4 | // Source* : https://leetcode.com/problems/binary-tree-level-order-traversal/ 5 | // Category* : BinaryTree BFS 6 | // 7 | // Created by Tianyu Wang on 16/7/3. 8 | // Github : http://github.com/wty21cn 9 | // Website : http://wty.im 10 | // Linkedin : https://www.linkedin.com/in/wty21cn 11 | // Mail : mailto:wty21cn@gmail.com 12 | 13 | 14 | /********************************************************************************** 15 | * 16 | * Given a binary tree, return the level order traversal of its nodes' values. 17 | * (ie, from left to right, level by level). 18 | * 19 | * For example: 20 | * Given binary tree {3,9,20,nil,nil,15,7}, 21 | * 22 | * 3 23 | * / \ 24 | * 9 20 25 | * / \ 26 | * 15 7 27 | * 28 | * return its level order traversal as: 29 | * 30 | * [ 31 | * [3], 32 | * [9,20], 33 | * [15,7] 34 | * ] 35 | ***********************************************************************************/ 36 | 37 | 38 | import Foundation 39 | 40 | struct q102 { 41 | 42 | class Solution { 43 | func levelOrder(_ root: TreeNode?) -> [[Int]] { 44 | var traversal: [[Int]] = [] 45 | if let root = root 46 | { 47 | var queue: [(TreeNode,Int)] = [(root,0)] 48 | var head = queue.startIndex, tail = queue.endIndex 49 | while head < tail { 50 | 51 | let (node, level) = queue[head] 52 | if level >= traversal.endIndex { traversal.append([]) } 53 | traversal[level].append(node.val) 54 | if let l = node.left { queue.append((l, level + 1)) } 55 | if let r = node.right { queue.append((r, level + 1)) } 56 | 57 | tail = queue.endIndex 58 | head = (head + 1) 59 | } 60 | 61 | } 62 | return traversal 63 | } 64 | } 65 | 66 | static func getSolution() -> Void { 67 | let root = BinaryTreeHelper.buildTree(withNodes: [3,9,20,nil,nil,15,7]) 68 | print(root ?? "") 69 | 70 | print(Solution().levelOrder(root)) 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /leetcode-swift/Easy/q107-binary-tree-level-order-traversal-ii.swift: -------------------------------------------------------------------------------- 1 | // 2 | // q107-binary-tree-level-order-traversal-ii.swift 3 | // leetcode-swift 4 | // Source* : https://leetcode.com/problems/binary-tree-level-order-traversal-ii/ 5 | // Category* : BinaryTree BFS 6 | // 7 | // Created by Tianyu Wang on 16/7/3. 8 | // Github : http://github.com/wty21cn 9 | // Website : http://wty.im 10 | // Linkedin : https://www.linkedin.com/in/wty21cn 11 | // Mail : mailto:wty21cn@gmail.com 12 | 13 | 14 | /********************************************************************************** 15 | * 16 | * Given a binary tree, return the bottom-up level order traversal of its nodes' values. 17 | * (ie, from left to right, level by level from leaf to root). 18 | * 19 | * For example: 20 | * Given binary tree {3,9,20,nil,nil,15,7}, 21 | * 22 | * 3 23 | * / \ 24 | * 9 20 25 | * / \ 26 | * 15 7 27 | * 28 | * return its bottom-up level order traversal as: 29 | * 30 | * [ 31 | * [15,7], 32 | * [9,20], 33 | * [3] 34 | * ] 35 | ***********************************************************************************/ 36 | 37 | 38 | import Foundation 39 | 40 | struct q107 { 41 | 42 | class Solution { 43 | func levelOrderBottom(_ root: TreeNode?) -> [[Int]] { 44 | var traversal: [[Int]] = [] 45 | if let root = root 46 | { 47 | var queue: [(TreeNode,Int)] = [(root,0)] 48 | var head = queue.startIndex, tail = queue.endIndex 49 | while head < tail { 50 | 51 | let (node, level) = queue[head] 52 | if level >= traversal.endIndex { traversal.append([]) } 53 | traversal[level].append(node.val) 54 | if let l = node.left { queue.append((l, level + 1)) } 55 | if let r = node.right { queue.append((r, level + 1)) } 56 | 57 | tail = queue.endIndex 58 | head = (head + 1) 59 | } 60 | 61 | } 62 | return traversal.reversed() 63 | } 64 | } 65 | 66 | static func getSolution() -> Void { 67 | let root = BinaryTreeHelper.buildTree(withNodes: [3,9,20,nil,nil,15,7]) 68 | print(root ?? "") 69 | print(Solution().levelOrderBottom(root)) 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /leetcode-swift/Medium/q122-best-time-to-buy-and-sell-stock-ii.swift: -------------------------------------------------------------------------------- 1 | // 2 | // q122-best-time-to-buy-and-sell-stock-ii.swift 3 | // leetcode-swift 4 | // Source : https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/ 5 | // Category* : Greedy 6 | // 7 | // Created by Tianyu Wang on 16/6/30. 8 | // Github : http://github.com/wty21cn 9 | // Website : http://wty.im 10 | // Linkedin : https://www.linkedin.com/in/wty21cn 11 | // Mail : mailto:wty21cn@gmail.com 12 | 13 | 14 | /********************************************************************************** 15 | * 16 | * Say you have an array for which the ith element is the price of a given stock on day i. 17 | * 18 | * Design an algorithm to find the maximum profit. You may complete as many transactions 19 | * as you like (ie, buy one and sell one share of the stock multiple times). However, 20 | * you may not engage in multiple transactions at the same time (ie, you must sell the 21 | * stock before you buy again). 22 | * 23 | **********************************************************************************/ 24 | 25 | /* 26 | 27 | Greedy Solution 28 | 29 | In Stock Game, You should always buy shares at the lowest price and sell it at the highest price. 30 | Apparently In real world you don't know the future. But for this question you do. 31 | 32 | So Everytime you see the price of tomorrow is low than today, you sell it and buy again tomorrow. 33 | 34 | */ 35 | 36 | 37 | import Foundation 38 | 39 | struct Q0122 { 40 | 41 | class Solution { 42 | func maxProfit(_ prices: [Int]) -> Int { 43 | 44 | var prices = prices 45 | prices.append(0) //take care of the last day. 46 | 47 | var minBuyingPrice = prices.first 48 | var totalProfit = 0 49 | for index in prices.indices.suffix(from: (prices.startIndex + 1)) { 50 | 51 | if prices[index] < prices[(index - 1)] { 52 | 53 | totalProfit += (prices[(index - 1)] - minBuyingPrice!) 54 | minBuyingPrice = prices[index] 55 | 56 | } 57 | } 58 | 59 | return totalProfit 60 | 61 | } 62 | } 63 | 64 | static func getSolution() -> Void { 65 | print(Solution().maxProfit([7,1,5,3,6,4])) 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /leetcode-swift/Easy/q205-isomorphic-strings.swift: -------------------------------------------------------------------------------- 1 | // 2 | // q205-isomorphic-strings.swift 3 | // leetcode-swift 4 | // Source* : https://leetcode.com/problems/isomorphic-strings/ 5 | // Category* : Hash 6 | // 7 | // Created by Tianyu Wang on 16/7/5. 8 | // Github : http://github.com/wty21cn 9 | // Website : http://wty.im 10 | // Linkedin : https://www.linkedin.com/in/wty21cn 11 | // Mail : mailto:wty21cn@gmail.com 12 | 13 | 14 | /********************************************************************************** 15 | * 16 | * Given two strings s and t, determine if they are isomorphic. 17 | * 18 | * Two strings are isomorphic if the characters in s can be replaced to get t. 19 | * 20 | * All occurrences of a character must be replaced with another character while preserving 21 | * the order of characters. No two characters may map to the same character but a character 22 | * may map to itself. 23 | * 24 | * For example, 25 | * 26 | * Given "egg", "add", return true. 27 | * 28 | * Given "foo", "bar", return false. 29 | * 30 | * Given "paper", "title", return true. 31 | * 32 | * Note: 33 | * You may assume both s and t have the same length. 34 | * 35 | **********************************************************************************/ 36 | 37 | 38 | import Foundation 39 | 40 | struct q205 { 41 | 42 | class Solution { 43 | func isIsomorphic(_ s: String, _ t: String) -> Bool { 44 | var hash = [Character:Character]() 45 | var map = Set() 46 | var s = Array(s.characters) 47 | var t = Array(t.characters) 48 | for i in s.indices.suffix(from: 0) { 49 | if let r = hash[s[i]] { 50 | if r != t[i] { 51 | return false 52 | } 53 | } else { 54 | if map.contains(t[i]) { 55 | return false 56 | } 57 | hash[s[i]] = t[i] 58 | map.insert(t[i]) 59 | } 60 | } 61 | return true 62 | } 63 | } 64 | 65 | static func getSolution() -> Void { 66 | print(Solution().isIsomorphic("egg", "add")) 67 | print(Solution().isIsomorphic("foo", "bar")) 68 | print(Solution().isIsomorphic("papre", "title")) 69 | print(Solution().isIsomorphic("ab", "aa")) 70 | 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /leetcode-swift/Easy/q345-reverse-vowels-of-a-string.swift: -------------------------------------------------------------------------------- 1 | // 2 | // q345-reverse-vowels-of-a-string.swift 3 | // leetcode-swift 4 | // Source* : https://leetcode.com/problems/reverse-vowels-of-a-string/ 5 | // Category* : String 6 | // 7 | // Created by Tianyu Wang on 16/7/2. 8 | // Github : http://github.com/wty21cn 9 | // Website : http://wty.im 10 | // Linkedin : https://www.linkedin.com/in/wty21cn 11 | // Mail : mailto:wty21cn@gmail.com 12 | 13 | 14 | /*************************************************************************************** 15 | * 16 | * Write a function that takes a string as input and reverse only the vowels of a 17 | * string. 18 | * 19 | * Example 1: 20 | * Given s = "hello", return "holle". 21 | * 22 | * Example 2: 23 | * Given s = "leetcode", return "leotcede". 24 | * 25 | ***************************************************************************************/ 26 | 27 | 28 | import Foundation 29 | 30 | struct q345 { 31 | 32 | class Solution { 33 | func reverseVowels(_ s: String) -> String { 34 | 35 | if s.isEmpty { 36 | return s 37 | } 38 | 39 | var s = s 40 | let vowels = "aAeEiIoOuU".characters 41 | var headIndex = s.startIndex 42 | var tailIndex = s.characters.index(before: s.endIndex) 43 | 44 | while headIndex < tailIndex{ 45 | while !vowels.contains(s[headIndex]) && headIndex < tailIndex { 46 | headIndex = s.index(after: headIndex) 47 | } 48 | 49 | while !vowels.contains(s[tailIndex]) && headIndex < tailIndex { 50 | tailIndex = s.index(before: tailIndex) 51 | } 52 | 53 | if headIndex == tailIndex { 54 | break 55 | } 56 | 57 | let tmp = s[headIndex] 58 | s.replaceSubrange(headIndex...headIndex, with: "\(s[tailIndex])") 59 | s.replaceSubrange(tailIndex...tailIndex, with: "\(tmp)") 60 | 61 | headIndex = s.index(after: headIndex) 62 | tailIndex = s.index(before: tailIndex) 63 | } 64 | return s 65 | } 66 | } 67 | 68 | static func getSolution() -> Void { 69 | print(Solution().reverseVowels("12")) 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /leetcode-swift/Easy/q160-majority-element.swift: -------------------------------------------------------------------------------- 1 | // 2 | // q160-majority-element.swift 3 | // leetcode-swift 4 | // Source* : https://leetcode.com/problems/majority-element/ 5 | // Category* : Array 6 | // 7 | // Created by Tianyu Wang on 16/6/28. 8 | // Github : http://github.com/wty21cn 9 | // Website : http://wty.im 10 | // Linkedin : https://www.linkedin.com/in/wty21cn 11 | // Mail : mailto:wty21cn@gmail.com 12 | 13 | 14 | /********************************************************************************** 15 | * 16 | * Given an array of size n, find the majority element. 17 | * The majority element is the element that appears more than ⌊ n/2 ⌋ times. 18 | * 19 | * You may assume that the array is non-empty and the majority element always exist in the array. 20 | * 21 | * Credits:Special thanks to @ts for adding this problem and creating all test cases. 22 | * 23 | **********************************************************************************/ 24 | 25 | 26 | import Foundation 27 | fileprivate func < (lhs: T?, rhs: T?) -> Bool { 28 | switch (lhs, rhs) { 29 | case let (l?, r?): 30 | return l < r 31 | case (nil, _?): 32 | return true 33 | default: 34 | return false 35 | } 36 | } 37 | 38 | fileprivate func > (lhs: T?, rhs: T?) -> Bool { 39 | switch (lhs, rhs) { 40 | case let (l?, r?): 41 | return l > r 42 | default: 43 | return rhs < lhs 44 | } 45 | } 46 | 47 | 48 | struct q169 { 49 | 50 | class Solution { 51 | func majorityElement(_ nums: [Int]) -> Int { 52 | var counter = [Int:Int]() 53 | var majority = 0 54 | let majorityCount = Int(floor(Double(nums.count)/2.0)) 55 | 56 | for num in nums { 57 | if let _ = counter[num] { 58 | counter[num]! += 1 59 | } else { 60 | counter[num] = 1 61 | } 62 | if counter[num] > majorityCount { 63 | majority = num 64 | } 65 | } 66 | return majority 67 | } 68 | } 69 | 70 | //Shorter but slower solution 71 | class Solution2 { 72 | func majorityElement(_ nums: [Int]) -> Int { 73 | return nums.sorted{ $0 < $1 }[nums.count/2] 74 | } 75 | } 76 | 77 | static func getSolution() -> Void { 78 | print(Solution2().majorityElement([1,2,2,2,2,3,3,3,3,3,3,4])) 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /leetcode-swift/Easy/q021-merge-two-sorted-lists.swift: -------------------------------------------------------------------------------- 1 | // 2 | // q021-merge-two-sorted-lists.swift 3 | // leetcode-swift 4 | // Source* : https://leetcode.com/problems/merge-two-sorted-lists/ 5 | // Category* : LinkedList TwoPointers 6 | // 7 | // Created by Tianyu Wang on 16/7/1. 8 | // Github : http://github.com/wty21cn 9 | // Website : http://wty.im 10 | // Linkedin : https://www.linkedin.com/in/wty21cn 11 | // Mail : mailto:wty21cn@gmail.com 12 | 13 | 14 | 15 | /********************************************************************************** 16 | * 17 | * Merge two sorted linked lists and return it as a new list. The new list should be 18 | * made by splicing together the nodes of the first two lists. 19 | * 20 | **********************************************************************************/ 21 | 22 | 23 | import Foundation 24 | 25 | struct q21 { 26 | 27 | class Solution { 28 | func mergeTwoLists(_ l1: ListNode?, _ l2: ListNode?) -> ListNode? { 29 | 30 | if l1 == nil { return l2 } 31 | if l2 == nil { return l1 } 32 | 33 | let head = l1!.val < l2!.val ? l1 : l2 // point to the head of merged list 34 | var tmp: ListNode? = nil // point to previous selected nodes 35 | var l1 = l1, l2 = l2 36 | 37 | while l1 != nil && l2 != nil { 38 | if l1!.val < l2!.val { 39 | tmp?.next = l1 40 | tmp = l1 41 | l1 = l1!.next 42 | } else { 43 | tmp?.next = l2 44 | tmp = l2 45 | l2 = l2!.next 46 | } 47 | } 48 | tmp?.next = l1 != nil ? l1 : l2 49 | return head 50 | } 51 | } 52 | 53 | static func getSolution() -> Void { 54 | 55 | var l1 = LinkedListHelper.buildLinkedList(withNodes: [1,5,8,9,13]) 56 | var l2 = LinkedListHelper.buildLinkedList(withNodes: [0,2,3,6,11,14]) 57 | 58 | print(Solution().mergeTwoLists(l1,l2) ?? "") 59 | 60 | l1 = LinkedListHelper.buildLinkedList(withNodes: [1,2,3,4,5]) 61 | l2 = LinkedListHelper.buildLinkedList(withNodes: [1,2,3,4,5,6]) 62 | print(Solution().mergeTwoLists(l1, l2) ?? "") 63 | 64 | 65 | l1 = LinkedListHelper.buildLinkedList(withNodes: [1,2,3,4,5]) 66 | l2 = nil 67 | print(Solution().mergeTwoLists(l1, l2) ?? "") 68 | 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /leetcode-swift/Easy/q342-power-of-four.swift: -------------------------------------------------------------------------------- 1 | // 2 | // q342-power-of-four.swift 3 | // leetcode-swift 4 | // Source* : https://leetcode.com/problems/power-of-four/ 5 | // Category* : Math BitManipulation 6 | // 7 | // Created by Tianyu Wang on 16/7/3. 8 | // Github : http://github.com/wty21cn 9 | // Website : http://wty.im 10 | // Linkedin : https://www.linkedin.com/in/wty21cn 11 | // Mail : mailto:wty21cn@gmail.com 12 | 13 | /*************************************************************************************** 14 | * 15 | * Given an integer (signed 32 bits), write a function to check whether it is a power 16 | * of 4. 17 | * 18 | * Example: 19 | * Given num = 16, return true. 20 | * Given num = 5, return false. 21 | * 22 | * Follow up: Could you solve it without loops/recursion? 23 | * 24 | * Credits:Special thanks to @yukuairoy for adding this problem and creating all test 25 | * cases. 26 | ***************************************************************************************/ 27 | 28 | 29 | /* 30 | 31 | If a number is a power of 4 32 | 33 | 1.first it should be a power of 2, so check num & (num -1) 34 | 2.For the binary format of this number, the number of 0 on the right of 1 should be even. 35 | 36 | */ 37 | 38 | import Foundation 39 | 40 | struct q342 { 41 | 42 | class Solution { 43 | func isPowerOfFour(_ num: Int) -> Bool { 44 | 45 | if num <= 0 { return false } 46 | 47 | var num = num 48 | if num & (num - 1) == 0 { 49 | var numOfZero = 0 50 | while num & 0b1 == 0 { 51 | numOfZero += 1 52 | num >>= 1 53 | } 54 | if numOfZero % 2 == 0 { 55 | return true 56 | } else { 57 | return false 58 | } 59 | } else { 60 | return false 61 | } 62 | } 63 | } 64 | 65 | class SolutionFollowUp { 66 | func isPowerOfFour(_ num: Int) -> Bool { 67 | if num <= 0 { return false } 68 | 69 | if num & (num - 1) == 0 { 70 | let check = 0b10101010101010101010101010101010 71 | return num & check == 0 72 | 73 | } else { 74 | return false 75 | } 76 | } 77 | } 78 | 79 | static func getSolution() -> Void { 80 | print(Solution().isPowerOfFour(8)) 81 | print(SolutionFollowUp().isPowerOfFour(8)) 82 | } 83 | } 84 | -------------------------------------------------------------------------------- /leetcode-swift/Easy/q299-bulls-and-cows.swift: -------------------------------------------------------------------------------- 1 | // 2 | // q299-bulls-and-cows.swift 3 | // leetcode-swift 4 | // Source* : https://leetcode.com/problems/bulls-and-cows/ 5 | // Category* : Hash 6 | // 7 | // Created by Tianyu Wang on 16/7/4. 8 | // Github : http://github.com/wty21cn 9 | // Website : http://wty.im 10 | // Linkedin : https://www.linkedin.com/in/wty21cn 11 | // Mail : mailto:wty21cn@gmail.com 12 | 13 | 14 | import Foundation 15 | 16 | struct q299 { 17 | 18 | class Solution { 19 | func getHint(_ secret: String, _ guess: String) -> String { 20 | 21 | var cows = 0 22 | var bulls = 0 23 | 24 | let secret = Array(secret.characters) 25 | let guess = Array(guess.characters) 26 | 27 | var digitsCount = Dictionary() 28 | 29 | //count the num of each digit 30 | for i in 0.. Void { 64 | print(Solution().getHint("1123", "0111")) 65 | print(Solution().getHint("1807", "7810")) 66 | print(Solution().getHint("11", "11")) 67 | print(Solution().getHint("1122", "2211")) 68 | print(Solution().getHint("1222", "1122")) 69 | print(Solution().getHint("6244988279", "3819888600")) 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /leetcode-swift/Easy/q206-reverse-linked-list.swift: -------------------------------------------------------------------------------- 1 | // 2 | // q206-reverse-linked-list.swift 3 | // leetcode-swift 4 | // Source : https://leetcode.com/problems/reverse-linked-list/ 5 | // Category* : LinkedList TwoPointers 6 | // 7 | // Created by Tianyu Wang on 16/6/27. 8 | // Github : http://github.com/wty21cn 9 | // Website : http://wty.im 10 | // Linkedin : https://www.linkedin.com/in/wty21cn 11 | // Mail : mailto:wty21cn@gmail.com 12 | 13 | 14 | /********************************************************************************** 15 | * 16 | * Reverse a singly linked list. 17 | * 18 | * click to show more hints. 19 | * 20 | * Hint: 21 | * A linked list can be reversed either iteratively or recursively. Could you implement both? 22 | * 23 | * 24 | **********************************************************************************/ 25 | 26 | 27 | import Foundation 28 | 29 | struct q206 { 30 | 31 | class Solution { 32 | func reverseList(_ head: ListNode?) -> ListNode? { 33 | 34 | return reverseListRecursively(head) 35 | 36 | } 37 | 38 | func reverseListRecursively(_ head: ListNode?) -> ListNode? { 39 | if let head = head { 40 | 41 | if head.next == nil { 42 | return head 43 | } 44 | 45 | let reversedListHead = reverseListRecursively(head.next) 46 | 47 | head.next?.next = head 48 | head.next = nil 49 | 50 | return reversedListHead 51 | } else { 52 | return nil 53 | } 54 | } 55 | 56 | } 57 | 58 | class Solution2 { 59 | 60 | func reverseList(_ head: ListNode?) -> ListNode? { 61 | return reverseListInteratively(head) 62 | } 63 | 64 | func reverseListInteratively(_ head: ListNode?) -> ListNode? { 65 | var head = head 66 | var n: ListNode? = head?.next 67 | var p: ListNode? = nil 68 | while head != nil { 69 | 70 | head!.next = p 71 | p = head 72 | head = n 73 | n = head?.next 74 | 75 | } 76 | return p 77 | } 78 | } 79 | 80 | static func getSolution() -> Void { 81 | let head = LinkedListHelper.buildLinkedList(withNodes: [1,2]) 82 | print(head ?? "") 83 | 84 | let reversedListHead = Solution2().reverseList(head) 85 | print(reversedListHead ?? "") 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /leetcode-swift/Easy/q202-happy-number.swift: -------------------------------------------------------------------------------- 1 | // 2 | // q202-happy-number.swift 3 | // leetcode-swift 4 | // Source* : https://leetcode.com/problems/happy-number/ 5 | // Category* : Math Hash 6 | // 7 | // Created by Tianyu Wang on 16/6/29. 8 | // Github : http://github.com/wty21cn 9 | // Website : http://wty.im 10 | // Linkedin : https://www.linkedin.com/in/wty21cn 11 | // Mail : mailto:wty21cn@gmail.com 12 | 13 | 14 | 15 | /********************************************************************************** 16 | * 17 | * Write an algorithm to determine if a number is "happy". 18 | * 19 | * A happy number is a number defined by the following process: Starting with any positive integer, 20 | * replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 21 | * (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this 22 | * process ends in 1 are happy numbers. 23 | * 24 | * Example: 19 is a happy number 25 | * 26 | * 1^2 + 9^2 = 82 27 | * 8^2 + 2^2 = 68 28 | * 6^2 + 8^2 = 100 29 | * 1^2 + 0^2 + 0^2 = 1 30 | * 31 | * Credits:Special thanks to @mithmatt and @ts for adding this problem and creating all test cases. 32 | * 33 | **********************************************************************************/ 34 | 35 | 36 | import Foundation 37 | 38 | struct q202 { 39 | 40 | class Solution { 41 | 42 | var hashTable: Set! 43 | 44 | func isHappy(_ n: Int) -> Bool { 45 | hashTable = Set() 46 | var n = n 47 | while true { 48 | var digits = [Int]() 49 | while n != 0 { 50 | digits.append(n % 10) 51 | n /= 10 52 | } 53 | 54 | if exist(digits) { return false } 55 | 56 | for digit in digits { 57 | n += (digit * digit) 58 | } 59 | 60 | if n == 1 { return true } 61 | } 62 | 63 | } 64 | 65 | func exist(_ digits: [Int]) -> Bool { 66 | let digits = digits.sorted() 67 | var hash = "" 68 | for digit in digits { 69 | hash += "\(digit)" 70 | } 71 | if hashTable.contains(hash) { 72 | return true 73 | } else { 74 | hashTable.insert(hash) 75 | return false 76 | } 77 | 78 | } 79 | 80 | } 81 | 82 | static func getSolution() -> Void { 83 | print(Solution().isHappy(8)) 84 | } 85 | } 86 | -------------------------------------------------------------------------------- /leetcode-swift/Easy/q290-word-pattern.swift: -------------------------------------------------------------------------------- 1 | // 2 | // q290-word-pattern.swift 3 | // leetcode-swift 4 | // Source* : https://leetcode.com/problems/word-pattern/ 5 | // Category* : Hash 6 | // 7 | // Created by Tianyu Wang on 16/7/5. 8 | // Github : http://github.com/wty21cn 9 | // Website : http://wty.im 10 | // Linkedin : https://www.linkedin.com/in/wty21cn 11 | // Mail : mailto:wty21cn@gmail.com 12 | 13 | 14 | /*************************************************************************************** 15 | * 16 | * Given a pattern and a string str, find if str follows the same pattern. 17 | * Here follow means a full match, such that there is a bijection between a letter in 18 | * pattern and a non-empty word in str. 19 | * 20 | * Examples: 21 | * 22 | * pattern = "abba", str = "dog cat cat dog" should return true. 23 | * pattern = "abba", str = "dog cat cat fish" should return false. 24 | * pattern = "aaaa", str = "dog cat cat dog" should return false. 25 | * pattern = "abba", str = "dog dog dog dog" should return false. 26 | * 27 | * Notes: 28 | * You may assume pattern contains only lowercase letters, and str contains lowercase 29 | * letters separated by a single space. 30 | * 31 | * Credits:Special thanks to @minglotus6 for adding this problem and creating all test 32 | * cases. 33 | * 34 | ***************************************************************************************/ 35 | 36 | 37 | import Foundation 38 | 39 | struct q290 { 40 | 41 | class Solution { 42 | 43 | fileprivate var patternRules = [Character:[Int]]() 44 | fileprivate var patternKey = Set() 45 | 46 | func wordPattern(_ pattern: String, _ str: String) -> Bool { 47 | 48 | for (i, char) in pattern.characters.enumerated() { 49 | if patternRules[char] != nil { 50 | patternRules[char]!.append(i) 51 | } else { 52 | patternRules[char] = [i] 53 | } 54 | } 55 | 56 | let words = str.components(separatedBy: " ") 57 | 58 | if words.count != pattern.characters.count { return false } 59 | 60 | for (_, patternRule) in patternRules { 61 | let key: String = words[patternRule.first!] 62 | for i in patternRule { 63 | if key != words[i] { return false } 64 | } 65 | if patternKey.contains(key) { 66 | return false 67 | } else { 68 | patternKey.insert(key) 69 | } 70 | } 71 | return true 72 | } 73 | } 74 | 75 | static func getSolution() -> Void { 76 | print(Solution().wordPattern("abba", "dog cat cat fish")) 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /leetcode-swift/Easy/q198-house-robber.swift: -------------------------------------------------------------------------------- 1 | // 2 | // q198-house-robber.swift 3 | // leetcode-swift 4 | // Source* : https://leetcode.com/problems/house-robber/ 5 | // Category* : DynamicProgramming 6 | // 7 | // Created by Tianyu Wang on 16/7/3. 8 | // Github : http://github.com/wty21cn 9 | // Website : http://wty.im 10 | // Linkedin : https://www.linkedin.com/in/wty21cn 11 | // Mail : mailto:wty21cn@gmail.com 12 | 13 | 14 | /********************************************************************************** 15 | * 16 | * You are a professional robber planning to rob houses along a street. Each house has 17 | * a certain amount of money stashed, the only constraint stopping you from robbing 18 | * each of them is that adjacent houses have security system connected and it will 19 | * automatically contact the police if two adjacent houses were broken into on the same night. 20 | * 21 | * Given a list of non-negative integers representing the amount of money of each house, 22 | * determine the maximum amount of money you can rob tonight without alerting the police. 23 | * 24 | * 25 | **********************************************************************************/ 26 | 27 | /* 28 | 29 | Dynamic Programming 30 | 31 | formula : dp[i] = max(dp[i - 2] + nums[i], dp[i - 1]) 32 | boundary : dp[0] = nums[0], dp[1] = max(dp[0], nums[1]) 33 | explaination: 34 | For the most value you can rob when you are at house i, you have two options, 35 | 1.Robbing house i, which means you didn't rob house i - 1 36 | 2.Giving up house i, which means you can get the same value when when you chose to rob house i - 1 37 | 38 | Solution2 optimize space from O(N) to O(1) 39 | 40 | */ 41 | 42 | import Foundation 43 | 44 | struct q198 { 45 | 46 | class Solution { 47 | func rob(_ nums: [Int]) -> Int { 48 | if nums.isEmpty { return 0 } 49 | if nums.count == 1 { return nums[0] } 50 | 51 | var dp = Array(repeating: 0, count: nums.count) 52 | dp[0] = nums[0] 53 | dp[1] = max(dp[0], nums[1]) 54 | for index in nums.indices.suffix(from: 2) { 55 | dp[index] = max(dp[index - 1], dp[index - 2] + nums[index]) 56 | } 57 | return dp.last! 58 | } 59 | } 60 | 61 | class Solution2 { 62 | func rob(_ nums: [Int]) -> Int { 63 | var dp1 = 0 64 | var dp2 = 0 65 | for index in nums.indices { 66 | let current = max(dp1, dp2 + nums[index]) 67 | dp2 = dp1 68 | dp1 = current 69 | } 70 | return dp1 71 | } 72 | } 73 | 74 | static func getSolution() -> Void { 75 | print(Solution().rob([1,2,3,4,5,1,2,3,4,5])) 76 | print(Solution2().rob([1,2,3,4,5,1,2,3,4,5])) 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /leetcode-swift/Easy/q112-path-sum.swift: -------------------------------------------------------------------------------- 1 | // 2 | // q112-path-sum.swift 3 | // leetcode-swift 4 | // Source* : https://leetcode.com/problems/path-sum/ 5 | // Category* : DFS 6 | // 7 | // Created by Tianyu Wang on 16/7/4. 8 | // Github : http://github.com/wty21cn 9 | // Website : http://wty.im 10 | // Linkedin : https://www.linkedin.com/in/wty21cn 11 | // Mail : mailto:wty21cn@gmail.com 12 | 13 | 14 | /********************************************************************************** 15 | * 16 | * Given a binary tree and a sum, determine if the tree has a root-to-leaf path 17 | * such that adding up all the values along the path equals the given sum. 18 | * 19 | * For example: 20 | * Given the below binary tree and sum = 22, 21 | * 22 | * 5 23 | * / \ 24 | * 4 8 25 | * / / \ 26 | * 11 13 4 27 | * / \ \ 28 | * 7 2 1 29 | * 30 | * return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22. 31 | * 32 | **********************************************************************************/ 33 | 34 | /* 35 | 36 | DFS 37 | 38 | takecare that the path must be a root-to-leaf path and the node.val may be negetive 39 | 40 | */ 41 | 42 | 43 | import Foundation 44 | 45 | struct q112 { 46 | 47 | class Solution { 48 | 49 | func dfs(_ node: TreeNode?, currentSum: Int, sum: Int) -> Bool { 50 | if let node = node { 51 | 52 | let currentSum = currentSum + node.val 53 | 54 | let lResult = dfs(node.left, currentSum: currentSum, sum: sum) 55 | let rResult = dfs(node.right, currentSum: currentSum, sum: sum) 56 | 57 | switch (node.left, node.right) { 58 | case (nil,nil): 59 | return lResult && rResult 60 | case (nil, _): 61 | return rResult 62 | case (_, nil): 63 | return lResult 64 | case (_, _): 65 | return lResult || rResult 66 | } 67 | 68 | 69 | } else { 70 | return currentSum == sum 71 | } 72 | } 73 | 74 | func hasPathSum(_ root: TreeNode?, _ sum: Int) -> Bool { 75 | if let root = root { 76 | return dfs(root, currentSum: 0, sum: sum) 77 | } else { 78 | return false 79 | } 80 | } 81 | } 82 | 83 | static func getSolution() -> Void { 84 | let root = BinaryTreeHelper.buildTree(withNodes: [5,4,8,11,nil,13,4,7,2,nil,1]) 85 | print(root ?? "") 86 | 87 | print(Solution().hasPathSum(root, 22)) 88 | print(Solution().hasPathSum(root, 9)) 89 | } 90 | } 91 | -------------------------------------------------------------------------------- /leetcode-swift/Easy/q225-implement-stack-using-queues.swift: -------------------------------------------------------------------------------- 1 | // 2 | // q225-implement-stack-using-queues.swift 3 | // leetcode-swift 4 | // Source* : https://leetcode.com/problems/implement-stack-using-queues/ 5 | // Category* : Stack Queue 6 | // 7 | // Created by Tianyu Wang on 16/7/4. 8 | // Github : http://github.com/wty21cn 9 | // Website : http://wty.im 10 | // Linkedin : https://www.linkedin.com/in/wty21cn 11 | // Mail : mailto:wty21cn@gmail.com 12 | 13 | 14 | /********************************************************************************** 15 | * 16 | * Implement the following operations of a stack using queues. 17 | * 18 | * push(x) -- Push element x onto stack. 19 | * 20 | * pop() -- Removes the element on top of the stack. 21 | * 22 | * top() -- Get the top element. 23 | * 24 | * empty() -- Return whether the stack is empty. 25 | * 26 | * Notes: 27 | * 28 | * You must use only standard operations of a queue -- which means only push to back, 29 | * peek/pop from front, size, and is empty operations are valid. 30 | * 31 | * Depending on your language, queue may not be supported natively. You may simulate 32 | * a queue by using a list or deque (double-ended queue), as long as you use only 33 | * standard operations of a queue. 34 | * 35 | * You may assume that all operations are valid (for example, no pop or top operations 36 | * will be called on an empty stack). 37 | * 38 | * Update (2015-06-11): 39 | * The class name of the Java function had been updated to MyStack instead of Stack. 40 | * 41 | * Credits:Special thanks to @jianchao.li.fighter for adding this problem and all test cases. 42 | * 43 | **********************************************************************************/ 44 | 45 | 46 | import Foundation 47 | 48 | struct q225 { 49 | 50 | class Stack { 51 | 52 | var queue = [Int]() 53 | var tmpQueue = [Int]() 54 | 55 | func push(_ n: Int) -> Void { 56 | queue.append(n) 57 | } 58 | 59 | func pop() -> Void { 60 | 61 | while queue.count > 0 { 62 | tmpQueue.append(queue.removeFirst()) 63 | } 64 | 65 | queue.removeFirst() 66 | 67 | while tmpQueue.count >= 0 { 68 | queue.append(queue.removeFirst()) 69 | } 70 | } 71 | 72 | func top() -> Int { 73 | 74 | while queue.count > 0 { 75 | tmpQueue.append(queue.removeFirst()) 76 | } 77 | 78 | let n = queue.removeFirst() 79 | tmpQueue.append(n) 80 | 81 | while tmpQueue.count >= 0 { 82 | queue.append(tmpQueue.removeFirst()) 83 | } 84 | return n 85 | } 86 | 87 | func isEmpty() -> Bool { 88 | return queue.isEmpty 89 | } 90 | 91 | } 92 | 93 | static func getSolution() -> Void { 94 | } 95 | } 96 | -------------------------------------------------------------------------------- /leetcode-swift/Easy/q232-implement-queue-using-stacks.swift: -------------------------------------------------------------------------------- 1 | // 2 | // q232-implement-queue-using-stacks.swift 3 | // leetcode-swift 4 | // Source* : https://leetcode.com/problems/implement-queue-using-stacks/ 5 | // Category* : Queue Stack 6 | // 7 | // Created by Tianyu Wang on 16/7/4. 8 | // Github : http://github.com/wty21cn 9 | // Website : http://wty.im 10 | // Linkedin : https://www.linkedin.com/in/wty21cn 11 | // Mail : mailto:wty21cn@gmail.com 12 | 13 | 14 | /********************************************************************************** 15 | * 16 | * Implement the following operations of a queue using stacks. 17 | * 18 | * push(x) -- Push element x to the back of queue. 19 | * 20 | * pop() -- Removes the element from in front of queue. 21 | * 22 | * peek() -- Get the front element. 23 | * 24 | * empty() -- Return whether the queue is empty. 25 | * 26 | * Notes: 27 | * 28 | * You must use only standard operations of a stack -- which means only push to top, 29 | * peek/pop from top, size, and is empty operations are valid. 30 | * Depending on your language, stack may not be supported natively. You may simulate a 31 | * stack by using a list or deque (double-ended queue), as long as you use only 32 | * standard operations of a stack. 33 | * You may assume that all operations are valid (for example, no pop or peek operations 34 | * will be called on an empty queue). 35 | * 36 | **********************************************************************************/ 37 | 38 | 39 | import Foundation 40 | 41 | struct q232 { 42 | 43 | class Queue { 44 | 45 | var stack: [Int] = [] 46 | var tmpStack: [Int] = [] 47 | 48 | 49 | func push(_ n: Int) -> Void { 50 | stack.append(n) 51 | } 52 | 53 | func pop() -> Int { 54 | 55 | while stack.count != 1 { 56 | tmpStack.append((stack.removeLast())) 57 | } 58 | 59 | let h = stack.removeLast() 60 | 61 | while tmpStack.count != 0 { 62 | stack.append(tmpStack.removeLast()) 63 | } 64 | 65 | return h 66 | } 67 | 68 | func pick() -> Int { 69 | while stack.count != 1 { 70 | tmpStack.append((stack.removeLast())) 71 | } 72 | 73 | let h = stack.last 74 | 75 | while tmpStack.count != 0 { 76 | stack.append(tmpStack.removeLast()) 77 | } 78 | 79 | return h! 80 | 81 | } 82 | 83 | func isEmpty() -> Bool { 84 | return stack.isEmpty 85 | } 86 | } 87 | 88 | static func getSolution() -> Void { 89 | 90 | let queue = Queue() 91 | queue.push(1); queue.push(2); queue.push(3); queue.push(4); 92 | print(queue.pop()); print(queue.pop()); print(queue.pop()); print(queue.pop()); 93 | print(queue.isEmpty()) 94 | 95 | } 96 | } 97 | -------------------------------------------------------------------------------- /leetcode-swift/Easy/q013-roman-to-integer.swift: -------------------------------------------------------------------------------- 1 | // 2 | // q013-roman-to-integer.swift 3 | // leetcode-swift 4 | // Source* : https://leetcode.com/problems/roman-to-integer/ 5 | // Category* : String Math 6 | // 7 | // Created by Tianyu Wang on 16/6/28. 8 | // Github : http://github.com/wty21cn 9 | // Website : http://wty.im 10 | // Linkedin : https://www.linkedin.com/in/wty21cn 11 | // Mail : mailto:wty21cn@gmail.com 12 | 13 | 14 | 15 | /********************************************************************************** 16 | * 17 | * Given a roman numeral, convert it to an integer. 18 | * 19 | * Input is guaranteed to be within the range from 1 to 3999. 20 | * 21 | **********************************************************************************/ 22 | 23 | /* 24 | 25 | 1.相同的数字连写,所表示的数等于这些数字相加得到的数,如 Ⅲ=3; 26 | 2.小的数字在大的数字的右边,所表示的数等于这些数字相加得到的数,如 Ⅷ=8、Ⅻ=12; 27 | 3.小的数字(限于 Ⅰ、X 和 C)在大的数字的左边,所表示的数等于大数减小数得到的数,如 Ⅳ=4、Ⅸ=9; 28 | 4.在一个数的上面画一条横线,表示这个数增值 1,000 倍; 29 | 注意:从右往左按规则进行计数 30 | 31 | */ 32 | 33 | 34 | import Foundation 35 | fileprivate func < (lhs: T?, rhs: T?) -> Bool { 36 | switch (lhs, rhs) { 37 | case let (l?, r?): 38 | return l < r 39 | case (nil, _?): 40 | return true 41 | default: 42 | return false 43 | } 44 | } 45 | 46 | fileprivate func > (lhs: T?, rhs: T?) -> Bool { 47 | switch (lhs, rhs) { 48 | case let (l?, r?): 49 | return l > r 50 | default: 51 | return rhs < lhs 52 | } 53 | } 54 | 55 | 56 | struct q13 { 57 | 58 | class Solution { 59 | func romanToInt(_ s: String) -> Int { 60 | 61 | let romanUnit = [Character("I"):1, Character("V"):5, Character("X"):10, 62 | Character("L"):50, Character("C"):100, Character("D"):500, 63 | Character("M"):1000] 64 | 65 | let reversedChars = s.characters.reversed() 66 | var integer = 0 67 | var index = reversedChars.startIndex 68 | while index != reversedChars.endIndex { 69 | let char1 = reversedChars[index] 70 | if reversedChars.index(after: index) == reversedChars.endIndex { 71 | integer += romanUnit[char1]! 72 | break 73 | } 74 | let char2 = reversedChars[reversedChars.index(after: index)] 75 | 76 | if romanUnit[char1] > romanUnit[char2] && ["I", "C", "X"].contains(String(char2)) { 77 | 78 | integer = integer + romanUnit[char1]! - romanUnit[char2]! 79 | index = reversedChars.index(index, offsetBy: 2) 80 | 81 | } else { 82 | 83 | integer += romanUnit[char1]! 84 | index = reversedChars.index(after: index) 85 | 86 | } 87 | } 88 | 89 | return integer 90 | } 91 | } 92 | 93 | static func getSolution() -> Void { 94 | print(Solution().romanToInt("MCMXCVI")) 95 | } 96 | } 97 | -------------------------------------------------------------------------------- /leetcode-swift/Easy/q235-lowest-common-ancestor-of-a-binary-search-tree.py: -------------------------------------------------------------------------------- 1 | #! _*_encoding:utf-8_*_ 2 | ''' 3 | q235-lowest-common-ancestor-of-a-binary-search-tree.py 4 | leetcode-swift 5 | Source* : https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/ 6 | Category* : BinaryTree BinarySearchTree 7 | 8 | Created by Tianyu Wang on 16/6/29. 9 | Github : http://github.com/wty21cn 10 | Website : http://wty.im 11 | Linkedin : https://www.linkedin.com/in/wty21cn 12 | Mail : mailto:wty21cn@gmail.com 13 | ''' 14 | 15 | ''' 16 | /********************************************************************************** 17 | * 18 | * Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given 19 | * nodes in the BST. 20 | * 21 | * According to the definition of LCA on Wikipedia: “The lowest common ancestor is 22 | * defined between two nodes v and w as the lowest node in T that has both v and w as 23 | * descendants (where we allow a node to be a descendant of itself).” 24 | * 25 | * _______6______ 26 | * / \ 27 | * ___2__ ___8__ 28 | * / \ / \ 29 | * 0 _4 7 9 30 | * / \ 31 | * 3 5 32 | * 33 | * For example, the lowest common ancestor (LCA) of nodes 2 and 8 is 6. Another example 34 | * is LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself according 35 | * to the LCA definition. 36 | * 37 | * 38 | **********************************************************************************/ 39 | ''' 40 | 41 | class TreeNode(object): 42 | def __init__(self, x): 43 | self.val = x 44 | self.left = None 45 | self.right = None 46 | 47 | 48 | class Solution(object): 49 | def lowestCommonAncestor(self, root, p, q): 50 | """ 51 | :type root: TreeNode 52 | :type p: TreeNode 53 | :type q: TreeNode 54 | :rtype: TreeNode 55 | """ 56 | result = self.findLCA(root, p, q) 57 | return result[1] 58 | 59 | 60 | def findLCA(self, node, p, q): 61 | """ 62 | :type root: TreeNode 63 | :type p: TreeNode 64 | :type q: TreeNode 65 | :rtype: (Int, TreeNode) 66 | """ 67 | total_number = 0 68 | if node.val == p.val or node.val == q.val: 69 | if p.val == q.val: 70 | return (2, node) 71 | total_number += 1 72 | if node.left: 73 | result = self.findLCA(node.left, p, q) 74 | if result[0] == 2: 75 | return result 76 | else: 77 | total_number += result[0] 78 | 79 | if total_number == 2: 80 | return (2, node) 81 | 82 | if node.right: 83 | result = self.findLCA(node.right, p, q) 84 | if result[0] == 2: 85 | return result 86 | else: 87 | total_number += result[0] 88 | 89 | if total_number == 2: 90 | return (2, node) 91 | 92 | return (total_number, None) 93 | 94 | 95 | if __name__ == "__main__": 96 | root = TreeNode(2) 97 | root.left = TreeNode(1) 98 | 99 | 100 | print(Solution().lowestCommonAncestor(root, TreeNode(1), TreeNode(2)).val) -------------------------------------------------------------------------------- /leetcode-swift/Easy/q234-palindrome-linked-list.swift: -------------------------------------------------------------------------------- 1 | // 2 | // q234-palindrome-linked-list.swift 3 | // leetcode-swift 4 | // Source* : https://leetcode.com/problems/palindrome-linked-list/ 5 | // Category* : LinkedList TwoPointers 6 | // 7 | // Created by Tianyu Wang on 16/7/7. 8 | // Github : http://github.com/wty21cn 9 | // Website : http://wty.im 10 | // Linkedin : https://www.linkedin.com/in/wty21cn 11 | // Mail : mailto:wty21cn@gmail.com 12 | 13 | 14 | /********************************************************************************** 15 | * 16 | * Given a singly linked list, determine if it is a palindrome. 17 | * 18 | * Follow up: 19 | * Could you do it in O(n) time and O(1) space? 20 | * 21 | **********************************************************************************/ 22 | 23 | 24 | import Foundation 25 | 26 | struct q234 { 27 | 28 | class Solution { 29 | func findHalfOfLink(_ head: ListNode?) -> ListNode? { 30 | var head = head 31 | var fastPtr = head 32 | while fastPtr?.next != nil { 33 | head = head!.next 34 | fastPtr = fastPtr!.next!.next 35 | } 36 | return head 37 | } 38 | 39 | func reverse(_ head: ListNode?) -> ListNode? { 40 | var head = head 41 | var p: ListNode? = nil 42 | var n: ListNode? = head?.next 43 | 44 | while head != nil { 45 | head!.next = p 46 | p = head 47 | head = n 48 | n = head?.next 49 | } 50 | return p 51 | } 52 | 53 | func isPalindrome(_ head: ListNode?) -> Bool{ 54 | var halfHead = reverse(findHalfOfLink(head)) 55 | var head = head 56 | 57 | while head != nil && halfHead != nil { 58 | guard head!.val == halfHead!.val else { 59 | return false 60 | } 61 | head = head!.next 62 | halfHead = halfHead!.next 63 | } 64 | return true 65 | } 66 | } 67 | 68 | // This Solution will crash when the link is very long. 69 | class Solution_StackOverFlow { 70 | var ptr: ListNode? 71 | 72 | func isPalindromeUtil(_ node: ListNode) -> Bool { 73 | 74 | if let next = node.next { 75 | guard isPalindromeUtil(next) else { 76 | return false 77 | } 78 | } 79 | 80 | guard ptr!.val == node.val else { 81 | return false 82 | } 83 | 84 | ptr = ptr!.next 85 | return true 86 | } 87 | 88 | func isPalindrome(_ head: ListNode?) -> Bool { 89 | 90 | if let head = head { 91 | ptr = head 92 | return isPalindromeUtil(head) 93 | } else { 94 | return true 95 | } 96 | } 97 | } 98 | static func getSolution() -> Void { 99 | let head = LinkedListHelper.buildLinkedList(withNodes: [1,1,2,1,1]) 100 | print(head ?? "") 101 | print(Solution().isPalindrome(head)) 102 | } 103 | } 104 | -------------------------------------------------------------------------------- /leetcode-swift/Easy/q223-rectangle-area.swift: -------------------------------------------------------------------------------- 1 | // 2 | // q223-rectangle-area.swift 3 | // leetcode-swift 4 | // Source* : https://leetcode.com/problems/rectangle-area/ 5 | // Category* : Geometry 6 | // 7 | // Created by Tianyu Wang on 16/7/4. 8 | // Github : http://github.com/wty21cn 9 | // Website : http://wty.im 10 | // Linkedin : https://www.linkedin.com/in/wty21cn 11 | // Mail : mailto:wty21cn@gmail.com 12 | 13 | 14 | /********************************************************************************** 15 | * 16 | * Find the total area covered by two rectilinear rectangles in a 2D plane. 17 | * Each rectangle is defined by its bottom left corner and top right corner as shown in the figure. 18 | * 19 | * Y 20 | * ^ 21 | * | 22 | * | 23 | * | 24 | * | (C,D):(3,4) 25 | * +------------------+ 26 | * | | | 27 | * | | | 28 | * | | | (G,H):(9,2) 29 | * | +----------------------------+ 30 | * | | | | 31 | * | | | | 32 | * | | | | 33 | * +---------|--------+-------------------|---------> X 34 | * (A,B):(-3,0) | | 35 | * +----------------------------+ 36 | * (E,F):(0,-1) 37 | * 38 | * 39 | * 40 | * Assume that the total area is never beyond the maximum possible value of int. 41 | * 42 | * Credits:Special thanks to @mithmatt for adding this problem, creating the above image and all test cases. 43 | * 44 | **********************************************************************************/ 45 | 46 | 47 | import Foundation 48 | 49 | struct q223 { 50 | 51 | class Solution { 52 | 53 | class Rectangle { 54 | var bottomLeft: (x: Int, y: Int)! 55 | var topRight: (x: Int, y: Int)! 56 | 57 | init(bottomLeftX: Int, bottomLeftY: Int, topRightX: Int, topRightY: Int) { 58 | bottomLeft = (bottomLeftX, bottomLeftY) 59 | topRight = (topRightX, topRightY) 60 | } 61 | 62 | func intersectArea(_ rect: Rectangle) -> Int { 63 | let x = max(0, min(topRight.x, rect.topRight.x) - max(bottomLeft.x, rect.bottomLeft.x)) 64 | let y = max(0, min(topRight.y, rect.topRight.y) - max(bottomLeft.y, rect.bottomLeft.y)) 65 | return x * y 66 | } 67 | 68 | func area() -> Int { 69 | return (topRight.x - bottomLeft.x) * (topRight.y - bottomLeft.y) 70 | } 71 | 72 | } 73 | 74 | func computeArea(_ A: Int, _ B: Int, _ C: Int, _ D: Int, _ E: Int, _ F: Int, _ G: Int, _ H: Int) -> Int { 75 | 76 | let rectA = Rectangle(bottomLeftX: A,bottomLeftY: B,topRightX: C,topRightY: D) 77 | let rectB = Rectangle(bottomLeftX: E,bottomLeftY: F,topRightX: G,topRightY: H) 78 | return rectA.area() + rectB.area() - rectA.intersectArea(rectB) 79 | 80 | 81 | 82 | } 83 | } 84 | 85 | static func getSolution() -> Void { 86 | print(Solution().computeArea(0, 0, 2, 2, -1, -1, 1, 1)) 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /leetcode-swift/Shared/BinaryTreeHelper.swift: -------------------------------------------------------------------------------- 1 | // 2 | // BinaryTreePrinter.swift 3 | // leetcode-swift 4 | // 5 | // Created by Tianyu Wang on 16/6/29. 6 | // Github : http://github.com/wty21cn 7 | // Website : http://wty.im 8 | // Linkedin : https://www.linkedin.com/in/wty21cn 9 | // Mail : mailto:wty21cn@gmail.com 10 | 11 | import Foundation 12 | 13 | //MARK: - Helper Protocol 14 | 15 | protocol BinaryTreeNodePrintable { 16 | func leftSubTree() -> BinaryTreeNodePrintable? 17 | func rightSubTree() -> BinaryTreeNodePrintable? 18 | func presentation() -> String 19 | } 20 | 21 | class BinaryTreeHelper { 22 | static func buildTree(withNodes nodes: [Int?]) -> TreeNode? { 23 | let root = buildTree(withNodes: nodes, index: nodes.startIndex) 24 | return root 25 | } 26 | 27 | fileprivate static func buildTree(withNodes nodes: [Int?], index: Int) -> TreeNode? { 28 | if index < nodes.endIndex { 29 | if let nodeValue = nodes[index] { 30 | let node = TreeNode(nodeValue) 31 | node.left = buildTree(withNodes: nodes, index: index * 2 + 1) 32 | node.right = buildTree(withNodes: nodes, index: index * 2 + 2) 33 | return node 34 | } else { 35 | return nil 36 | } 37 | } else { 38 | return nil 39 | } 40 | } 41 | } 42 | 43 | extension BinaryTreeHelper { 44 | 45 | fileprivate static let indentStrVertical = " │ " 46 | fileprivate static let indentStrBlank = " " 47 | fileprivate static let indentStrLine = "───── " 48 | fileprivate static let indentStrRightChild = " ┌" 49 | fileprivate static let indentStrLeftChild = " └" 50 | 51 | static func getStructureDescription(forNode node: BinaryTreeNodePrintable?) -> String { 52 | var description = "\n" 53 | if let root = node { 54 | if let rc = root.rightSubTree() { 55 | description += getSubtreeStructureDescription(rc, isRightSubtree: true, indent: "") 56 | } 57 | 58 | description += root.presentation() + "\n" 59 | 60 | if let lc = root.leftSubTree() { 61 | description += getSubtreeStructureDescription(lc, isRightSubtree: false, indent: "") 62 | } 63 | } else { 64 | description = "nil" 65 | } 66 | return description 67 | } 68 | 69 | fileprivate static func getSubtreeStructureDescription(_ subtree: BinaryTreeNodePrintable, isRightSubtree: Bool, indent: String) -> String { 70 | 71 | var description = "" 72 | 73 | let leftSubtreeIndent = indent + (isRightSubtree ? indentStrVertical : indentStrBlank) 74 | let rightSubTreeIndent = indent + (isRightSubtree ? indentStrBlank : indentStrVertical) 75 | let fullIndent = indent + (isRightSubtree ? indentStrRightChild : indentStrLeftChild) + indentStrLine 76 | 77 | if let rc = subtree.rightSubTree() { 78 | description += getSubtreeStructureDescription(rc, isRightSubtree: true, indent: rightSubTreeIndent) 79 | } 80 | 81 | description += fullIndent + subtree.presentation() + "\n" 82 | 83 | if let lc = subtree.leftSubTree() { 84 | description += getSubtreeStructureDescription(lc, isRightSubtree: false, indent: leftSubtreeIndent) 85 | } 86 | return description 87 | } 88 | 89 | } 90 | -------------------------------------------------------------------------------- /leetcode-swift/Easy/q036-valid-sudoku.swift: -------------------------------------------------------------------------------- 1 | // 2 | // q036-valid-sudoku.swift 3 | // leetcode-swift 4 | // Source* : https://leetcode.com/problems/valid-sudoku/ 5 | // Category* : Hash 6 | // 7 | // Created by Tianyu Wang on 16/7/4. 8 | // Github : http://github.com/wty21cn 9 | // Website : http://wty.im 10 | // Linkedin : https://www.linkedin.com/in/wty21cn 11 | // Mail : mailto:wty21cn@gmail.com 12 | 13 | 14 | /********************************************************************************** 15 | * 16 | * Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules. 17 | * 18 | * The Sudoku board could be partially filled, where empty cells are filled with the character '.'. 19 | * 20 | * A partially filled sudoku which is valid. 21 | * 22 | * Note: 23 | * > A valid Sudoku board (partially filled) is not necessarily solvable. 24 | * Only the filled cells need to be validated. 25 | * 26 | **********************************************************************************/ 27 | 28 | 29 | import Foundation 30 | 31 | struct q36 { 32 | 33 | class Solution { 34 | 35 | var ruleRow = [Set](repeating: Set(), count: 9) 36 | var ruleColumn = [Set](repeating: Set(), count: 9) 37 | var ruleSquare = [Set](repeating: Set(), count: 9) 38 | 39 | func isValidSudoku(_ board: [[Character]]) -> Bool { 40 | 41 | var indexOfRow = board.startIndex 42 | while indexOfRow != board.endIndex { 43 | 44 | var row = board[indexOfRow] 45 | var indexOfChar = row.startIndex 46 | while indexOfChar != row.endIndex { 47 | 48 | let char = row[indexOfChar] 49 | if char != "." { 50 | let passRuleRow = !ruleRow[indexOfRow].contains(char) 51 | let passRuleColumn = !ruleColumn[indexOfChar].contains(char) 52 | let passRuleSquare = !ruleSquare[(indexOfRow / 3) * 3 + indexOfChar / 3].contains(char) 53 | if passRuleRow && passRuleColumn && passRuleSquare { 54 | ruleRow[indexOfRow].insert(char) 55 | ruleColumn[indexOfChar].insert(char) 56 | ruleSquare[(indexOfRow / 3) * 3 + indexOfChar / 3].insert(char) 57 | indexOfChar = (indexOfChar + 1) 58 | } else { 59 | return false 60 | } 61 | } else { 62 | indexOfChar = (indexOfChar + 1) 63 | } 64 | } 65 | indexOfRow = (indexOfRow + 1) 66 | } 67 | return true 68 | } 69 | } 70 | 71 | static func getSolution() -> Void { 72 | let row1 = Array("..4...63.".characters) 73 | let row2 = Array(".........".characters) 74 | let row3 = Array("5......9.".characters) 75 | let row4 = Array("...56....".characters) 76 | let row5 = Array("4.3.....1".characters) 77 | let row6 = Array("...7.....".characters) 78 | let row7 = Array("...5.....".characters) 79 | let row8 = Array(".........".characters) 80 | let row9 = Array(".........".characters) 81 | print(Solution().isValidSudoku([row1,row2,row3,row4,row5,row6,row7,row8,row9])) 82 | } 83 | } 84 | -------------------------------------------------------------------------------- /leetcode-swift/Easy/q350-intersection-of-two-arrays-ii.swift: -------------------------------------------------------------------------------- 1 | // 2 | // q350-intersection-of-two-arrays-ii.swift 3 | // leetcode-swift 4 | // Source* : https://leetcode.com/problems/intersection-of-two-arrays-ii/ 5 | // Category* : Hash 6 | // 7 | // Created by Tianyu Wang on 16/6/28. 8 | // Github : http://github.com/wty21cn 9 | // Website : http://wty.imhttps://www.linkedin.com/in/wty21cn 10 | // Linkedin : 11 | // Mail : mailto:wty21cn@gmail.com 12 | 13 | 14 | /*************************************************************************************** 15 | * 16 | * Given two arrays, write a function to compute their intersection. 17 | * 18 | * Example: 19 | * Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2, 2]. 20 | * 21 | * Note: 22 | * Each element in the result should appear as many times as it shows in both arrays. 23 | * The result can be in any order. 24 | * 25 | * Follow up: 26 | * What if the given array is already sorted? How would you optimize your algorithm? 27 | * What if nums1's size is small compared to num2's size? Which algorithm is better? 28 | * What if elements of nums2 are stored on disk, and the memory is limited such that you 29 | * cannot load all elements into the memory at once? 30 | * 31 | ***************************************************************************************/ 32 | 33 | 34 | import Foundation 35 | 36 | struct q350 { 37 | 38 | class Solution { 39 | 40 | func intersect(_ nums1: [Int], _ nums2: [Int]) -> [Int] { 41 | let hashDict1 = makeHashDict(nums1) 42 | let hashDict2 = makeHashDict(nums2) 43 | var interSection = [Int]() 44 | for (num, time1) in hashDict1 { 45 | if let time2 = hashDict2[num] { 46 | let time = min(time1, time2) 47 | for _ in 0..