Skip to content

Instantly share code, notes, and snippets.

@tuzaiz
Created November 27, 2017 16:41
Show Gist options
  • Save tuzaiz/68a132a4909e854e9a17576fa11119f4 to your computer and use it in GitHub Desktop.
Save tuzaiz/68a132a4909e854e9a17576fa11119f4 to your computer and use it in GitHub Desktop.
Exam of Oursky
func isSubset(_ a: [Character], _ b: [Character]) -> Bool {
return b.filter({ (item) -> Bool in
return a.index(of: item) != nil
}).count == b.count
}
isSubset(["A", "B", "C", "D"], ["A", "C"])
isSubset(["A","B","C","D","E"], ["A","D","Z"])
isSubset(["A","D","E"], ["A","A","D","E"])

Answer: O(n^2)

In swift, filter an array means a loop to determine each item available, so the time complexity is O(n) And find an index in an array is the same, time complexity is O(n) .count and equal operation is all constant, so they are O(1)

So the total time complexity is O(n^2)

func nextFibonacci(numbers: [Int]) -> [Int] {
let sortedNumbers = numbers.sorted()
guard let min = sortedNumbers.first,
let max = sortedNumbers.last else {
return []
}
var prevFibonacci = 1
var fibonacci = 1
var fibonacciNumbers = [1,1]
while fibonacci < max {
let nextFibonacci = prevFibonacci + fibonacci
prevFibonacci = fibonacci
fibonacci = nextFibonacci
fibonacciNumbers.append(nextFibonacci)
}
return numbers.map { (n) -> Int in
for f in fibonacciNumbers {
if f > n {
return f
}
}
preconditionFailure()
}
}
nextFibonacci(numbers: [1, 9, 22])
function createArrayOfFunctions(y) {
var arr = [];
for(var i = 0; i<y; i++) {
arr[i] = function(x) { return x + i; }(i); // The bug is here
}
return arr;
}
// in the for loop, the value of elements are functions not numbers
// So I add (i) after it to get the return value and assign into arr
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment