diff --git a/Math/PlusOne.swift b/Math/PlusOne.swift new file mode 100644 index 00000000..709917a5 --- /dev/null +++ b/Math/PlusOne.swift @@ -0,0 +1,26 @@ +/** + * Question Link: https://leetcode.com/problems/plus-one/ + * Primary idea: Iterate and change the array from last to the first + * + * Time Complexity: O(n), Space Complexity: O(1) + */ + +class PlusOne { + func plusOne(digits: [Int]) -> [Int] { + var digits = digits + var index = digits.count - 1 + + while index >= 0 { + if digits[index] < 9 { + digits[index] += 1 + return digits + } + + digits[index] = 0 + index -= 1 + } + + digits.insert(1, atIndex: 0) + return digits + } +} \ No newline at end of file diff --git a/Math/UglyNumberII.swift b/Math/UglyNumberII.swift new file mode 100644 index 00000000..ac44a573 --- /dev/null +++ b/Math/UglyNumberII.swift @@ -0,0 +1,38 @@ +/** + * Question Link: https://leetcode.com/problems/ugly-number-ii/ + * Primary idea: Use three indices to build a helper array + * Time Complexity: O(n), Space Complexity: O(n) + * + */ + +class UglyNumberII { + func nthUglyNumber(n: Int) -> Int { + guard n > 1 else { + return 1 + } + + var uglyNums = [Int](count: n, repeatedValue: 1) + + var index2 = 0 + var index3 = 0 + var index5 = 0 + + for i in 1 ..< n { + var minVal = min(uglyNums[index2] * 2, uglyNums[index3] * 3, uglyNums[index5] * 5) + + if minVal == uglyNums[index2] * 2 { + index2 += 1 + } + if minVal == uglyNums[index3] * 3 { + index3 += 1 + } + if minVal == uglyNums[index5] * 5{ + index5 += 1 + } + + uglyNums[i] = minVal + } + + return uglyNums[n - 1] + } +} \ No newline at end of file