3.14 rise longest sequence

topic

A disorder of a given integer array, the length of the longest found rising sequence.

Examples

输入: [10,9,2,5,3,7,101,18]
输出: 4 
解释: 最长的上升子序列是 [2,3,7,101],它的长度是 4。

A thought

  • O ( n 2 ) O (n ^ 2)
  • Record length of the sequence number at the end of each of the longest sub-sequence with a rise in the array.
  • For the current position, before each of a number of traversal, each find their number is smaller than, get a sub-sequence of a rise, to take the longest to the current position as the end of the longest sequence length increase.

Code 1

class Solution {
public:
    int lengthOfLIS(vector<int>& nums) {
        if ( nums.size() == 0 ) return 0;

        int res = 1;
        vector<int> dp( nums.size(), 1 );

        for ( int i = 1; i < nums.size(); ++i ) {
            for ( int j = 0; j < i; ++j ) {
                if ( nums[i] > nums[j] ) {
                    dp[i] = max( dp[i], dp[j] + 1);
                }
            }

            res = max( dp[i], res );
        }

        return res;
    }
};	

Ideas two

  • Complexity of O (nlgn)
  • Maintain an array s. Through the array, the first array of filled first value s is empty.
  • Through the array, the array is the number of current num,
    • If the number is greater than s tail num, num into the s.
    • If s is less than num tail number, find a number just greater than the first and in the s num num and exchange.
  • This step can search using the binary.
  • S is the length of the final length of the longest rising sequence.

Code 2

class Solution {
public:
    int lengthOfLIS(vector<int>& nums) {
        if ( nums.size() < 2 ) return nums.size();

        vector<int> tail; // 以i为结尾的最长子序列。
        tail.reserve( nums.size() );
        tail.push_back( nums[0] );
        int end = 0;

        for ( int i = 1; i < nums.size(); ++i ) {
            if ( nums[i] > tail[end] ) {
                tail.push_back( nums[i] );
                ++end;
            }
            else {
                // i前面找到第一个大于nums[i]的数并替换
                int index = getFirst( tail, end, nums[i] );
                tail[index] = nums[i];
            }
        }

        return end + 1;
    }

    int getFirst( vector<int>& tail, int end, int target ) {
        int start = 0;

        while ( start < end ) {
            int mid = ( start + end ) >> 1;

            if ( tail[mid] >= target ) 
                end = mid;
            else
                start = mid + 1;
        }
        
        return start;
    }
};
He published 183 original articles · won praise 43 · views 60000 +

Guess you like

Origin blog.csdn.net/m0_37822685/article/details/104883114