Skip to content

Commit

Permalink
Merge branch 'master' into Math
Browse files Browse the repository at this point in the history
  • Loading branch information
Yi Gu committed Feb 11, 2017
2 parents 60e95b2 + c245e0f commit 09c78f7
Show file tree
Hide file tree
Showing 44 changed files with 1,191 additions and 230 deletions.
53 changes: 53 additions & 0 deletions Array/GameLife.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
/**
* Question Link: https://leetcode.com/problems/game-of-life/
* Primary idea: Divide whole things to 4 cases, change 1 to 2 and 0 to 3 to avoid
* overrite issues, and then use %2 to get final results
*
* Time Complexity: O(n), Space Complexity: O(1)
*
*/

class GameLife {
func gameOfLife(_ board: inout [[Int]]) {
guard board.count > 0 else {
return
}

let m = board.count, n = board[0].count

for i in 0 ..< m {
for j in 0 ..< n {
changeStatus(&board, i, j, m, n)
}
}

board = board.map { $0.map { $0 % 2 } }
}

private func changeStatus(_ board: inout [[Int]], _ i: Int, _ j: Int, _ m: Int, _ n: Int) {
var liveNum = 0

for x in i - 1 ... i + 1 {
for y in j - 1 ... j + 1 {
if x < 0 || x >= m || y < 0 || y >= n {
continue
}
if x == i && y == j {
continue
}

liveNum = board[x][y] == 1 || board[x][y] == 2 ? liveNum + 1 : liveNum
}
}

if board[i][j] == 1 {
if liveNum < 2 || liveNum > 3 {
board[i][j] = 2
}
} else {
if liveNum == 3 {
board[i][j] = 3
}
}
}
}
23 changes: 23 additions & 0 deletions Array/Heaters.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
/**
* Question Link: https://leetcode.com/problems/heaters/
* Primary idea: Two pointers, get the closest heater for the house, and update radius
* Time Complexity: O(nlogn), Space Complexity: O(1)
*
*/

class Heaters {
func findRadius(_ houses: [Int], _ heaters: [Int]) -> Int {
var i = 0, radius = 0
let houses = houses.sorted(), heaters = heaters.sorted()

for house in houses {
while i < heaters.count - 1 && 2 * house >= heaters[i] + heaters[i + 1] {
i += 1
}

radius = max(radius, abs(house - heaters[i]))
}

return radius
}
}
28 changes: 28 additions & 0 deletions Array/IslandPerimeter.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
/**
* Question Link: https://leetcode.com/problems/island-perimeter/
* Primary idea: Go through the matrix and check right and down neighbors.
* Time Complexity: O(nm), Space Complexity: O(1)
*
*/

class IslandPerimeter {
func islandPerimeter(_ grid: [[Int]]) -> Int {
var islands = 0, neighbors = 0

for i in 0 ..< grid.count {
for j in 0 ..< grid[0].count {
if grid[i][j] == 1 {
islands += 1
if i < grid.count - 1 && grid[i + 1][j] == 1 {
neighbors += 1
}
if (j < grid[0].count - 1 && grid[i][j + 1] == 1) {
neighbors += 1
}
}
}
}

return islands * 4 - neighbors * 2
}
}
21 changes: 10 additions & 11 deletions Array/MaximumSizeSubarraySumEqualsK.swift
Original file line number Diff line number Diff line change
Expand Up @@ -5,21 +5,20 @@
*/

class MaximumSizeSubarraySumEqualsK {
func maxSubArrayLen(nums: [Int], _ k: Int) -> Int {
var longestLen = 0
var dict = [Int: Int]()
dict[0] = -1
var sum = 0
func maxSubArrayLen(_ nums: [Int], _ k: Int) -> Int {
var longestLen = 0, sum = 0
var sumToIdx = [Int: Int]()
sumToIdx[0] = -1

for i in 0 ..< nums.count {
sum += nums[i]
for (i, num) in nums.enumerated() {
sum += num

if let lastIndex = dict[sum - k] {
longestLen = max(longestLen, i - lastIndex)
if let idx = sumToIdx[sum - k] {
longestLen = max(longestLen, i - idx)
}

guard let index = dict[sum] else {
dict[sum] = i
guard let idx = sumToIdx[sum] else {
sumToIdx[sum] = i
continue
}
}
Expand Down
23 changes: 12 additions & 11 deletions Array/MoveZeroes.swift
Original file line number Diff line number Diff line change
@@ -1,24 +1,25 @@
/**
* Question Link: https://leetcode.com/problems/move-zeroes/
* Primary idea: keep index zeroIndex, traverse through the array and swap the value
* Primary idea: keep index for element not equal to 0, traverse and set up the index
*
* Time Complexity: O(n), Space Complexity: O(1)
*
*/

class MoveZeroes {
func moveZeroes(_ nums: inout [Int]) {
var zeroIndex = 0

for i in 0 ..< nums.count {
if nums[i] != 0 {
_swap(&nums, i, zeroIndex)
zeroIndex += 1
var idx = 0
for (i, num) in nums.enumerated() {
if num != 0 {
nums[idx] = num
idx += 1
}
}
}

private func _swap<T>(_ nums: inout Array<T>, _ p: Int, _ q: Int) {
(nums[p], nums[q]) = (nums[q], nums[p])

while idx < nums.count {
nums[idx] = 0
idx += 1
}
}
}
51 changes: 51 additions & 0 deletions Array/NextPermutation.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
/**
* Question Link: https://leetcode.com/problems/next-permutation/
* Primary idea: Traverse the number from right to left, and replace the first smaller one
* with the least bigger one, then reverse all number afterwards
*
* Time Complexity: O(n), Space Complexity: O(1)
*
*/

class NextPermutation {
func nextPermutation(_ nums: inout [Int]) {
guard nums.count > 0 else {
return
}

var violate = -1

// find violate
for i in stride(from: nums.count - 1, to: 0, by: -1) {
if nums[i] > nums[i - 1] {
violate = i - 1
break
}
}

if violate != -1 {
for i in stride(from: nums.count - 1, to: violate, by: -1) {
if nums[i] > nums[violate] {
swap(&nums, i, violate)
break
}
}
}

reverse(&nums, violate + 1, nums.count - 1)
}

func reverse<T>(_ nums: inout [T], _ start: Int, _ end: Int) {
var start = start, end = end

while start < end {
swap(&nums, start, end)
start += 1
end -= 1
}
}

func swap<T>(_ nums: inout [T], _ p: Int, _ q: Int) {
(nums[p], nums[q]) = (nums[q], nums[p])
}
}
16 changes: 6 additions & 10 deletions Array/SetMatrixZeroes.swift
Original file line number Diff line number Diff line change
Expand Up @@ -11,18 +11,14 @@ class SetMatrixZeroes {
var rowHasZero = false, colHasZero = false
let m = matrix.count, n = matrix[0].count

for i in 0 ..< m {
if matrix[i][0] == 0 {
colHasZero = true
break
}
for i in 0 ..< m where matrix[i][0] == 0 {
colHasZero = true
break
}

for i in 0 ..< n {
if matrix[0][i] == 0 {
rowHasZero = true
break
}
for i in 0 ..< n where matrix[0][i] == 0 {
rowHasZero = true
break
}

for i in 1 ..< m {
Expand Down
16 changes: 6 additions & 10 deletions Array/SpiralMatrixII.swift
Original file line number Diff line number Diff line change
Expand Up @@ -6,21 +6,17 @@
*/

class SpiralMatrixII {
func generateMatrix(n: Int) -> [[Int]] {
func generateMatrix(_ n: Int) -> [[Int]] {
guard n > 0 else {
return [[Int]]()
}

var num = 1
var res = Array(count: n, repeatedValue: Array(count: n, repeatedValue: 0))

var start = 0
var end = 0
var offset = 0
var res = Array(repeating: Array(repeating: 0, count: n), count: n)

for layer in 0 ..< n / 2 {
start = layer
end = n - layer - 1
let start = layer
let end = n - layer - 1

// top
for i in start ..< end {
Expand All @@ -35,13 +31,13 @@ class SpiralMatrixII {
}

// bottom
for i in end.stride(to: start, by: -1) {
for i in stride(from: end, to: start, by: -1) {
res[end][i] = num
num += 1
}

// left
for i in end.stride(to: start, by: -1) {
for i in stride(from: end, to: start, by: -1) {
res[i][start] = num
num += 1
}
Expand Down
50 changes: 50 additions & 0 deletions DFS/ExpressionAddOperators.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
/**
* Question Link: https://leetcode.com/problems/expression-add-operators/
* Primary idea: Classic Depth-first Search, terminates at when position encounters the
* length of the string num, add to result when eval is equal to target
*
* Note:
* 1. String cast to Integer will make character loss, e.g. "05" -> 5
* 2. Multiplication's priority is higher than addiction
*
* Time Complexity: O(n!), Space Complexity: O(n)
*
*/

class ExpressionAddOperators {
func addOperators(_ num: String, _ target: Int) -> [String] {
var res = [String]()
let numChars = Array(num.characters)

guard numChars.count > 0 else {
return res
}

dfs(&res, "", numChars, target, 0, 0, 0)

return res
}

private func dfs(_ res: inout [String], _ temp: String, _ numChars: [Character], _ target: Int, _ pos: Int, _ eval: Int, _ mul: Int) {
if pos == numChars.count {
if eval == target {
res.append(temp)
}
return
}

for i in pos ..< numChars.count {
if i != pos && numChars[pos] == "0" {
break
}
let curt = Int(String(numChars[pos ..< i + 1]))!
if pos == 0 {
dfs(&res, temp + String(curt), numChars, target, i + 1, curt, curt)
} else {
dfs(&res, temp + "+" + String(curt), numChars, target, i + 1, eval + curt, curt)
dfs(&res, temp + "-" + String(curt), numChars, target, i + 1, eval - curt, -curt)
dfs(&res, temp + "*" + String(curt), numChars, target, i + 1, eval - mul + mul * curt, mul * curt)
}
}
}
}
10 changes: 4 additions & 6 deletions DFS/FactorCombinations.swift
Original file line number Diff line number Diff line change
Expand Up @@ -28,12 +28,10 @@ class FactorCombinations {
return
}

for i in start ... n {
if n % i == 0 {
path.append(i)
dfs(&res, &path, n / i, i)
path.removeLast()
}
for i in start ... n where n % i == 0 {
path.append(i)
dfs(&res, &path, n / i, i)
path.removeLast()
}
}
}
Loading

0 comments on commit 09c78f7

Please sign in to comment.