Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Solution for 754 & 1345 & 1457 #311

Open
wants to merge 10 commits into
base: master
Choose a base branch
from
8 changes: 8 additions & 0 deletions Array/CheckArrayFormationThroughConcatenation.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
class Solution {
func canFormArray(_ arr: [Int], _ pieces: [[Int]]) -> Bool {
var map = pieces.reduce(into: [Int:[Int]]()) { $0[arr.firstIndex(of: $1[0]) ?? 0] = $1 }
var smap = Array(map.sorted { $0.0 < $1.0 }.flatMap{ $0.1 })

return arr.hashValue == smap.hashValue
}
}
16 changes: 16 additions & 0 deletions Array/MaxNumberOfK-SumPairs.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
class Solution {
func maxOperations(_ nums: [Int], _ k: Int) -> Int {
var rest = [Int: Int]()
var result = 0
for num in nums {
if let count = rest[k-num], count > 0 {
rest[k-num] = count-1
result += 1
} else {
rest[num, default: 0] += 1
}
}

return result
}
}
49 changes: 49 additions & 0 deletions BFS/JumpGameIV.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
class Solution {
func minJumps(_ arr: [Int]) -> Int {
var map = [Int: [Int]]()
for i in 0..<arr.count {
map[arr[i], default: [Int]()].append(i)
}

var visited = Array(repeating: false, count: arr.count)
visited[0] = true
var steps = [0]

func appendQueue(_ index: Int) {
if !visited[index] {
steps.append(index)
visited[index] = true
}
}

for currentStep in 1...arr.count {
let doSteps = steps
steps = []
for num in doSteps {
// Reach
if num == (arr.count-1) {
return currentStep-1
}

// Right
if num < (arr.count-1) {
appendQueue(num+1)
}

// Left
if num > 0 {
appendQueue(num-1)
}

// Tail
let datas = map[arr[num]]!
for data in datas {
appendQueue(data)
}
map[arr[num]] = []
}
}

return 0
}
}
21 changes: 21 additions & 0 deletions DFS/BeautifulArrangement.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
class Solution {
func countArrangement(_ n: Int) -> Int {
var arr = Array(repeating: false, count: n)
return countArr(1, &arr)
}

func countArr(_ c: Int, _ arr: inout [Bool]) -> Int {
if c > arr.count { return 1 }

var count = 0
for x in 0..<arr.count {
if !arr[x] && ((x+1) % c == 0 || c % (x+1) == 0) {
arr[x] = true
count += countArr(c+1, &arr)
arr[x] = false
}
}

return count
}
}
17 changes: 17 additions & 0 deletions DP/BoatsToSavePeople.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
class Solution {
func numRescueBoats(_ people: [Int], _ limit: Int) -> Int {
var people = people.sorted()
var result = people.count
var l = 0, r = result-1

while l < r {
if people[l] + people[r] <= limit {
l += 1
result -= 1
}
r -= 1
}

return result
}
}
21 changes: 21 additions & 0 deletions DP/CountSortedVowelStrings.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
class Solution {
func countVowelStrings(_ n: Int) -> Int {
var curr = [0, 0, 0, 0, 1]

for _ in 1..<n {
var next = [Int]()
var sum = 0
for x in (0..<curr.count).reversed() {
sum += curr[x]
next.insert(sum, at:0)
}
curr = next
}

var result = 0
for x in 0..<curr.count {
result += curr[x] * (x+1)
}
return result
}
}
25 changes: 25 additions & 0 deletions DP/MinimumOperationsToReduceXToZero.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
class Solution {
func minOperations(_ nums: [Int], _ x: Int) -> Int {
var leftSums = [0: 0]

var leftSum = 0
for l in 0..<nums.count {
leftSum += nums[l]
if leftSums[leftSum] == nil {
leftSums[leftSum] = l + 1
}
}

var result = leftSums[x, default: Int.max]

var rightSum = 0
for r in (0..<nums.count).reversed() {
rightSum += nums[r]
if let l = leftSums[x-rightSum], r > l {
result = min(result, l + nums.count - r)
}
}

return result < Int.max ? result : -1
}
}
58 changes: 58 additions & 0 deletions LinkedList/PseudoPalindromicPathsInABinaryTree.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
/**
* Definition for a binary tree node.
* public class TreeNode {
* public var val: Int
* public var left: TreeNode?
* public var right: TreeNode?
* public init() { self.val = 0; self.left = nil; self.right = nil; }
* public init(_ val: Int) { self.val = val; self.left = nil; self.right = nil; }
* public init(_ val: Int, _ left: TreeNode?, _ right: TreeNode?) {
* self.val = val
* self.left = left
* self.right = right
* }
* }
*/
class Solution {
func pseudoPalindromicPaths (_ root: TreeNode?) -> Int {
var count = 0
goPath(Box(node: root!, path: [root!.val]), &count)
return count
}

func goPath(_ box: Box, _ count: inout Int) {
if box.node.left == nil && box.node.right == nil {
if box.path.count < 2 { count += 1 }
return
}

if box.node.left != nil {
var lBox = box
let lVal = lBox.node.left!.val
if lBox.path.contains(lVal) {
lBox.path.remove(lVal)
} else {
lBox.path.insert(lVal)
}
lBox.node = lBox.node.left!
goPath(lBox, &count)
}

if box.node.right != nil {
var rBox = box
let rVal = rBox.node.right!.val
if rBox.path.contains(rVal) {
rBox.path.remove(rVal)
} else {
rBox.path.insert(rVal)
}
rBox.node = rBox.node.right!
goPath(rBox, &count)
}
}

struct Box {
var node: TreeNode
var path: Set<Int>
}
}
26 changes: 26 additions & 0 deletions Math/ReachANumber.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
class Solution {
func reachNumber(_ target: Int) -> Int {
var target = abs(target)

var step = 0
while target > 0 {
step += 1
target -= step
}
target = -target

return (target.isMultiple(of: 2) ? step : (step + 1 + step%2))
}
}

/*
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21
1 2 3 4 5 6
2 3 4 5 6
3 4 5 6
3 4 5 6
4 5 6
4 5 6
*/


26 changes: 24 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,10 @@
## Array
| Title | Solution | Difficulty | Time | Space |
| ----- | -------- | ---------- | ---- | ----- |
[Max Number of K-Sum Pairs](https://leetcode.com/problems/max-number-of-k-sum-pairs/)|[Swift](./Array/MaxNumberOfK-SumPairs.swift)| Medium| O(n)| O(n)|
[Check Array Formation Through Concatenation](https://leetcode.com/problems/check-array-formation-through-concatenation/)|[Swift](./Array/CheckArrayFormationThroughConcatenation.swift)| Easy| O(nlogn)| O(n)|
[Verify an Alien Dictionary](https://leetcode.com/problems/verifying-an-alien-dictionary/)|[Swift](Array/VerifyingAlienDictionary.swift)| Easy| O(n)| O(n)|
[Sort Array By Parity](https://leetcode.com/problems/sort-array-by-parity/)|[Swift](Array/SortArrayByParity.swift)| Easy| O(n)| O(n)|
[Sort Array By Parity](https://leetcode.com/problems/sort-array-by-parity/)|[Swift](./Array/SortArrayByParity.swift)| Easy| O(n)| O(n)|
[Max Consecutive Ones](https://leetcode.com/problems/max-consecutive-ones/)| [Swift](./Array/MaxConsecutiveOnes.swift)| Easy| O(n)| O(1)|
[Heaters](https://leetcode.com/problems/heaters/)| [Swift](./Array/Heaters.swift)| Easy| O(nlogn)| O(1)|
[Number of Boomerangs](https://leetcode.com/problems/number-of-boomerangs/)| [Swift](./Array/NumberBoomerangs.swift)| Easy| O(n ^ 2)| O(n)|
Expand Down Expand Up @@ -102,6 +104,7 @@
## String
| Title | Solution | Difficulty | Time | Space |
| ----- | -------- | ---------- | ---- | ----- |
[Determine if Two Strings Are Close](https://leetcode.com/problems/determine-if-two-strings-are-close/)| [Swift](./String/DetermineIfTwoStringsAreClose.swift)| Medium| O(n^2)| O(n)|
[Fizz Buzz](https://leetcode.com/problems/fizz-buzz/)| [Swift](./String/FizzBuzz.swift)| Easy| O(n)| O(1)|
[First Unique Character in a String](https://leetcode.com/problems/first-unique-character-in-a-string/)| [Swift](./String/FirstUniqueCharacterInString.swift)| Easy| O(n)| O(1)|
[Keyboard Row](https://leetcode.com/problems/keyboard-row/)| [Swift](./String/KeyboardRow.swift)| Easy| O(nm)| O(n)|
Expand Down Expand Up @@ -159,10 +162,12 @@
[Partition List](https://leetcode.com/problems/partition-list/)| [Swift](./LinkedList/PartitionList.swift)| Medium| O(n)| O(1)|
[LRU Cache](https://leetcode.com/problems/lru-cache/) | [Swift](./LinkedList/LRUCache.swift) | Hard| O(1)| O(1)|
[LFU Cache](https://leetcode.com/problems/lfu-cache/) | [Swift](./LinkedList/LFUCache.swift) | Hard| O(1)| O(1)|
[Pseudo-Palindromic Paths in a Binary Tree](https://leetcode.com/problems/pseudo-palindromic-paths-in-a-binary-tree/) | [Swift](./LinkedList/PseudoPalindromicPathsInABinaryTree.swift) | Medium| O(n)| O(n)|

## Stack
| Title | Solution | Difficulty | Time | Space |
| ----- | -------- | ---------- | ---- | ----- |
[Largest Rectangle in Histogram](https://leetcode.com/problems/largest-rectangle-in-histogram/)| [Swift](./Stack/LargestRectangleInHistogram.swift)| Hard| O(n)| O(n)|
[Min Stack](https://leetcode.com/problems/min-stack/)| [Swift](./Stack/MinStack.swift)| Easy| O(1)| O(n)|
[Max Stack](https://leetcode.com/problems/max-stack/)| [Swift](./Stack/MaxStack.swift)| Easy| O(n)| O(n)|
[Valid Parentheses](https://leetcode.com/problems/valid-parentheses/)| [Swift](./Stack/ValidParentheses.swift)| Easy| O(n)| O(n)|
Expand Down Expand Up @@ -222,6 +227,9 @@
## Dynamic programming
| Title | Solution | Difficulty | Time | Space |
| ----- | -------- | ---------- | ---- | ----- |
[Count Sorted Vowel Strings](https://leetcode.com/problems/count-sorted-vowel-strings/) | [Swift](./DP/CountSortedVowelStrings.swift) | Medium| O(n)| O(n)|
[Minimum Operations to Reduce X to Zero](https://leetcode.com/problems/minimum-operations-to-reduce-x-to-zero/) | [Swift](./DP/MinimumOperationsToReduceXToZero.swift) | Medium| O(n)| O(n)|
[Boats to Save People](https://leetcode.com/problems/boats-to-save-people/) | [Swift](./DP/BoatsToSavePeople.swift) | Medium| O(nlogn)| O(n)|
[Nested List Weight Sum](https://leetcode.com/problems/nested-list-weight-sum/)| [Swift](./DP/NestedListWeightSum.swift)| Easy| O(n)| O(1)|
[Climbing Stairs](https://leetcode.com/problems/climbing-stairs/)| [Swift](./DP/ClimbingStairs.swift)| Easy| O(n)| O(1)|
[Min Cost Climbing Stairs](https://leetcode.com/problems/min-cost-climbing-stairs/)| [Swift](./DP/MinCostClimbingStairs.swift)| Easy| O(n)| O(n)|
Expand Down Expand Up @@ -271,6 +279,7 @@
## Depth-first search
| Title | Solution | Difficulty | Time | Space |
| ----- | -------- | ---------- | ---- | ----- |
[Beautiful Arrangement](https://leetcode.com/problems/beautiful-arrangement/)| [Swift](./DFS/BeautifulArrangement.swift)| Medium| O(n)| O(n)|
[Permutations](https://leetcode.com/problems/permutations/)| [Swift](./DFS/Permutations.swift)| Medium| O(n^n)| O(n)|
[Permutations II](https://leetcode.com/problems/permutations-ii/)| [Swift](./DFS/PermutationsII.swift)| Medium| O(n^n)| O(n)|
[Subsets](https://leetcode.com/problems/subsets/)| [Swift](./DFS/Subsets.swift)| Medium| O(n^n)| O(n)|
Expand Down Expand Up @@ -305,6 +314,7 @@
[Word Ladder](https://leetcode.com/problems/word-ladder/)| [Swift](./BFS/WordLadder.swift)| Medium| O(nm)| O(nm)|
[Evaluate Division](https://leetcode.com/problems/evaluate-division/)| [Swift](./BFS/EvaluateDivision.swift)| Medium| O(n^2)| O(n)|
[Shortest Distance from All Buildings](https://leetcode.com/problems/shortest-distance-from-all-buildings/)| [Swift](./BFS/ShortestDistanceAllBuildings.swift)| Hard| O((mn)^2)| O(mn)|
[Jump Game IV](https://leetcode.com/problems/jump-game-iv/)| [Swift](./BFS/JumpGameIV.swift)| Hard| O(n)| O(n)|

## Math
| Title | Solution | Difficulty | Time | Space |
Expand Down Expand Up @@ -348,6 +358,7 @@
[Permutation Sequence](https://leetcode.com/problems/permutation-sequence/)| [Swift](./Math/PermutationSequence.swift)| Medium| O(n^2)| O(1)|
[Line Reflection](https://leetcode.com/problems/line-reflection/)| [Swift](./Math/LineReflection.swift)| Medium| O(n)| O(n)|
[Valid Number](https://leetcode.com/problems/valid-number/)| [Swift](./Math/ValidNumber.swift)| Hard| O(n)| O(1)|
[Reach a Number](https://leetcode.com/problems/reach-a-number/)| [Swift](./Math/ReachANumber.swift)| Medium| O(logn)| O(1)|

## Search
| Title | Solution | Difficulty | Time | Space |
Expand Down Expand Up @@ -540,8 +551,19 @@
## Problem Status
| Solution | Number | Title | Difficulty |
| -------- | ------ | ----- | ---------- |
| [Swift](./Array/MaxNumberOfK-SumPairs.swift) | 1679 | [Max Number of K-Sum Pairs](https://leetcode.com/problems/max-number-of-k-sum-pairs/) | Medium |
| [Swift](./DP/MinimumOperationsToReduceXToZero.swift) | 1658 | [Minimum Operations to Reduce X to Zero](https://leetcode.com/problems/minimum-operations-to-reduce-x-to-zero/) | Medium |
| [Swift](./String/DetermineIfTwoStringsAreClose.swift) | 1657 | [Determine if Two Strings Are Close](https://leetcode.com/problems/determine-if-two-strings-are-close/) | Medium |
| [Swift](./DP/CountSortedVowelStrings.swift) | 1641 | [Count Sorted Vowel Strings](https://leetcode.com/problems/count-sorted-vowel-strings/) | Medium |
| [Swift](./Array/CheckArrayFormationThroughConcatenation.swift) | 1640 | [Check Array Formation Through Concatenation](https://leetcode.com/problems/check-array-formation-through-concatenation/) | Easy |
| [Swift](./LinkedList/PseudoPalindromicPathsInABinaryTree.swift) | 1457 | [Pseudo-Palindromic Paths in a Binary Tree](https://leetcode.com/problems/pseudo-palindromic-paths-in-a-binary-tree/) | Medium |
| [Swift](./BFS/JumpGameIV.swift) | 1345 | [Jump Game IV](https://leetcode.com/problems/jump-game-iv/) | Hard |
| [Swift](./DP/BoatsToSavePeople.swift) | 881 | [Boats to Save People](https://leetcode.com/problems/boats-to-save-people/) | Medium |
| [Swift](./Math/ReachANumber.swift) | 754 | [Reach a Number](https://leetcode.com/problems/reach-a-number/) | Medium |
| [Swift](./DFS/BeautifulArrangement.swift) | 526 | [Beautiful Arrangement](https://leetcode.com/problems/beautiful-arrangement/) | Medium |
| [Swift](./LinkedList/LFUCache.swift) | 460 | [LFU Cache](https://oj.leetcode.com/problems/lfu-cache/) | Hard |
| [Swift](./Array/FindDisappearedNumbers.swift)| 448| [Find All Numbers Disappeared in an Array](https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/)| Easy|
| [Swift](./String/FizzBuzz.swift) | 412 | [Fizz Buzz](https://leetcode.com/problems/fizz-buzz/) | Easy
| [Swift](./DFS/CombinationSumIV.swift) | 377 | [Combination Sum IV](https://leetcode.com/problems/combination-sum-iv/) | Medium
| | 376 | [Wiggle Subsequence](https://leetcode.com/problems/wiggle-subsequence/) | Medium
| [Swift](./DP/GuessNumberHigherOrLowerII.swift) | 375 | [Guess Number Higher or Lower II](https://leetcode.com/problems/guess-number-higher-or-lower-ii/) | Medium
Expand Down Expand Up @@ -818,7 +840,7 @@
| | 87 | [Scramble String](https://oj.leetcode.com/problems/scramble-string/) | Hard |
| [Swift](./LinkedList/PartitionList.swift) | 86 | [Partition List](https://oj.leetcode.com/problems/partition-list/) | Medium |
| | 85 | [Maximal Rectangle](https://oj.leetcode.com/problems/maximal-rectangle/) | Hard |
| | 84 | [Largest Rectangle in Histogram](https://oj.leetcode.com/problems/largest-rectangle-in-histogram/) | Hard |
| [Swift](./Stack/LargestRectangleInHistogram.swift) | 84 | [Largest Rectangle in Histogram](https://leetcode.com/problems/largest-rectangle-in-histogram/) | Hard |
| [Swift](./LinkedList/RemoveDuplicatesFromSortedList.swift) | 83 | [Remove Duplicates from Sorted List](https://oj.leetcode.com/problems/remove-duplicates-from-sorted-list/) | Easy |
| [Swift](./LinkedList/RemoveDuplicatesFromSortedListII.swift) | 82 | [Remove Duplicates from Sorted List II](https://oj.leetcode.com/problems/remove-duplicates-from-sorted-list-ii/) | Medium |
| [Swift](./Search/SearchInRotatedSortedArrayII.swift) | 81 | [Search in Rotated Sorted Array II](https://oj.leetcode.com/problems/search-in-rotated-sorted-array-ii/) | Medium |
Expand Down
19 changes: 19 additions & 0 deletions Stack/LargestRectangleInHistogram.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
class Solution {
func largestRectangleArea(_ heights: [Int]) -> Int {
var heights = [heights, [0]].flatMap{ $0 }
var result = 0
var stacks = [Int]()

for i in 0..<heights.count {
if !stacks.isEmpty && heights[i] < heights[stacks.last!] {
repeat {
let val = stacks.popLast()!
result = max(result, heights[val] * (stacks.isEmpty ? i : i-stacks.last!-1))
} while !stacks.isEmpty && heights[i] < heights[stacks.last!]
}
stacks.append(i)
}

return result
}
}
9 changes: 9 additions & 0 deletions String/DetermineIfTwoStringsAreClose.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
class Solution {
func closeStrings(_ word1: String, _ word2: String) -> Bool {
var dic1 = Dictionary(grouping: Array(word1)) { $0 }
var dic2 = Dictionary(grouping: Array(word2)) { $0 }

return dic1.map { $0.0 }.sorted() == dic2.map { $0.0 }.sorted()
&& dic1.map { $1.count }.sorted() == dic2.map { $1.count }.sorted()
}
}
Loading