Created
July 19, 2024 19:49
-
-
Save WhiteHyun/353e15e3571fb4f42bd31aebab5cb791 to your computer and use it in GitHub Desktop.
LeetCode - 300. Longest Increasing Subsequence using Greedy & Binary Search
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
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