标签:determine mission condition rate NPU other == fast temp
Given an unsorted array of integers, find the length of longest increasing subsequence.
Example:
Input: [10,9,2,5,3,7,101,18]
Output: 4
Explanation: The longest increasing subsequence is [2,3,7,101], therefore the length is 4.
Note:
There may be more than one LIS combination, it is only necessary for you to return the length.
Your algorithm should run in O(n2) complexity.
Follow up: Could you improve it to O(n log n) time complexity?
class Solution {
public:
int lengthOfLIS(vector<int>& nums) {
int len = nums.size();
if (len == 0) return 0;
int ans = 1;
vector<int> temp(len, 1);
for (int i = len-2; i >= 0; --i) {
for (int j = i; j < len; ++j) {
if (nums[i] < nums[j]) {
temp[i] = max(temp[i], temp[j] + 1);
}
}
ans = max(ans, temp[i]);
}
return ans;
}
};
Runtime: 24 ms, faster than 26.23% of C++ online submissions for Longest Increasing Subsequence.
class Solution {
public:
int lengthOfLIS(vector<int>& nums) {
vector<int> temp;
for (int i = 0; i < nums.size(); ++i) {
auto it = std::lower_bound(temp.begin(), temp.end(), nums[i]);
if (it == temp.end()) temp.push_back(nums[i]);
else *it = nums[i];
}
return temp.size();
}
};
Runtime: 4 ms, faster than 72.86% of C++ online submissions for Longest Increasing
Analysis:
lower_bound(temp.begin(), temp.end(), nums[i])
return the first element‘s address which more or equal to nums[i]
.
In this approach we use a vector to store the LIS nums.
Our strategy determined by the following conditions,
- If A[i] is smallest among all end
candidates of active lists, we will start
new active list of length 1.- If A[i] is largest among all end candidates of
active lists, we will clone the largest active
list, and extend it by A[i].
- If A[i] is in between, we will find a list with
largest end element that is smaller than A[i].
Clone and extend this list by A[i]. We will discard all
other lists of same length as that of this modified list.
here is an example:
It will be clear with an example, let us take example from wiki {0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15}.
A[0] = 0. Case 1. There are no active lists, create one.
A[1] = 8. Case 2. Clone and extend.
300. Longest Increasing Subsequence
标签:determine mission condition rate NPU other == fast temp
原文地址:https://www.cnblogs.com/ruruozhenhao/p/9898933.html