Skip to content

Commit

Permalink
[Math] add Solution to Plus One and Ugly Number II
Browse files Browse the repository at this point in the history
  • Loading branch information
Yi Gu committed Jun 22, 2016
1 parent b18753f commit ed06bed
Show file tree
Hide file tree
Showing 2 changed files with 64 additions and 0 deletions.
26 changes: 26 additions & 0 deletions Math/PlusOne.swift
Original file line number Diff line number Diff line change
@@ -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
}
}
38 changes: 38 additions & 0 deletions Math/UglyNumberII.swift
Original file line number Diff line number Diff line change
@@ -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]
}
}

0 comments on commit ed06bed

Please sign in to comment.