-
Notifications
You must be signed in to change notification settings - Fork 894
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
[Math] add Solution to Plus One and Ugly Number II
- Loading branch information
Yi Gu
committed
Jun 22, 2016
1 parent
b18753f
commit ed06bed
Showing
2 changed files
with
64 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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] | ||
} | ||
} |