|
| 1 | +# 300. Longest Increasing Subsequence |
| 2 | + |
| 3 | +- Difficulty: Medium. |
| 4 | +- Related Topics: Array, Binary Search, Dynamic Programming. |
| 5 | +- Similar Questions: Increasing Triplet Subsequence, Russian Doll Envelopes, Maximum Length of Pair Chain, Number of Longest Increasing Subsequence, Minimum ASCII Delete Sum for Two Strings, Minimum Number of Removals to Make Mountain Array, Find the Longest Valid Obstacle Course at Each Position, Minimum Operations to Make the Array K-Increasing, Longest Ideal Subsequence, Maximum Number of Books You Can Take, Longest Increasing Subsequence II. |
| 6 | + |
| 7 | +## Problem |
| 8 | + |
| 9 | +Given an integer array `nums`, return **the length of the longest **strictly increasing ********subsequence****. |
| 10 | + |
| 11 | + |
| 12 | +Example 1: |
| 13 | + |
| 14 | +``` |
| 15 | +Input: nums = [10,9,2,5,3,7,101,18] |
| 16 | +Output: 4 |
| 17 | +Explanation: The longest increasing subsequence is [2,3,7,101], therefore the length is 4. |
| 18 | +``` |
| 19 | + |
| 20 | +Example 2: |
| 21 | + |
| 22 | +``` |
| 23 | +Input: nums = [0,1,0,3,2,3] |
| 24 | +Output: 4 |
| 25 | +``` |
| 26 | + |
| 27 | +Example 3: |
| 28 | + |
| 29 | +``` |
| 30 | +Input: nums = [7,7,7,7,7,7,7] |
| 31 | +Output: 1 |
| 32 | +``` |
| 33 | + |
| 34 | + |
| 35 | +**Constraints:** |
| 36 | + |
| 37 | + |
| 38 | + |
| 39 | +- `1 <= nums.length <= 2500` |
| 40 | + |
| 41 | +- `-104 <= nums[i] <= 104` |
| 42 | + |
| 43 | + |
| 44 | + |
| 45 | +**Follow up:** Can you come up with an algorithm that runs in `O(n log(n))` time complexity? |
| 46 | + |
| 47 | + |
| 48 | +## Solution |
| 49 | + |
| 50 | +```javascript |
| 51 | +/** |
| 52 | + * @param {number[]} nums |
| 53 | + * @return {number} |
| 54 | + */ |
| 55 | +var lengthOfLIS = function(nums) { |
| 56 | + var arr = [nums[0]]; |
| 57 | + for (var i = 1; i < nums.length; i++) { |
| 58 | + if (nums[i] > arr[arr.length - 1]) { |
| 59 | + arr.push(nums[i]); |
| 60 | + } else { |
| 61 | + var index = binarySearch(arr, nums[i]); |
| 62 | + arr[index] = nums[i]; |
| 63 | + } |
| 64 | + } |
| 65 | + return arr.length; |
| 66 | +}; |
| 67 | + |
| 68 | +var binarySearch = function(arr, num) { |
| 69 | + var left = 0; |
| 70 | + var right = arr.length - 1; |
| 71 | + while (left < right) { |
| 72 | + var mid = left + Math.floor((right - left) / 2); |
| 73 | + if (arr[mid] > num) { |
| 74 | + right = mid; |
| 75 | + } else if (arr[mid] === num) { |
| 76 | + return mid; |
| 77 | + } else { |
| 78 | + left = mid + 1; |
| 79 | + } |
| 80 | + } |
| 81 | + return left; |
| 82 | +}; |
| 83 | +``` |
| 84 | + |
| 85 | +**Explain:** |
| 86 | + |
| 87 | +nope. |
| 88 | + |
| 89 | +**Complexity:** |
| 90 | + |
| 91 | +* Time complexity : O(n * log(n)). |
| 92 | +* Space complexity : O(n). |
0 commit comments