Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save WhiteHyun/353e15e3571fb4f42bd31aebab5cb791 to your computer and use it in GitHub Desktop.
Save WhiteHyun/353e15e3571fb4f42bd31aebab5cb791 to your computer and use it in GitHub Desktop.
LeetCode - 300. Longest Increasing Subsequence using Greedy & Binary Search
final class Solution {
func lengthOfLIS(_ nums: [Int]) -> Int {
var tails: [Int] = [nums[0]]
for index in 1 ..< nums.count {
if nums[index] > tails.last! {
tails.append(nums[index])
} else {
tails[binarySearch(tails, target: nums[index])] = nums[index]
}
}
return tails.count
}
private func binarySearch(_ arr: [Int], target: Int) -> Int {
var left = 0
var right = arr.count - 1
while left <= right {
let mid = (left + right) >> 1
if arr[mid] < target {
left = mid + 1
} else {
right = mid - 1
}
}
return left
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment