leetcode_300 Longest Increasing Subsequence,最长上升序列数

#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;

// 方法一:vector<pair<int,int>>有序数组统计法,时间复杂度n^2
class Solution {
public:
    int lengthOfLIS(vector<int>& nums) {
        vector<pair<int, int>> statistic;
        int returnMax = 0;
        for (int i = 0; i < nums.size(); ++i) {
            int j, tempMax = 0;
            for (j = 0; j < statistic.size(); ++j) {
                if (statistic[j].first >= nums[i]) {
                    break;
                }
                else {
                    tempMax = statistic[j].second > tempMax ? statistic[j].second : tempMax;
                }
            }
            tempMax += 1;
            returnMax = tempMax > returnMax ? tempMax : returnMax;
            statistic.insert(statistic.begin() + j, { nums[i],tempMax });
        }
        return returnMax;
    }
};

// 方法二:网友答案,动态规划法DP(比较难想),用到了c++ 中lower_bound()函数(返回大于等于val值的第一个元素的位置,底层算法用到了有序队列二分法查找),时间复杂度nlogn
class Solution {
public:
    int lengthOfLIS(vector<int>& nums) {
        if (nums.size() == 0) return 0;
        vector<int> DP;
        DP.push_back(nums[0]);
        for (int i =1 ; i < nums.size(); ++i) {
            if (nums[i] > DP.back()) {
                DP.push_back(nums[i]);
            }
            else {
                *(lower_bound(DP.begin(), DP.end(), nums[i])) = nums[i]; //直接替换返回位置的元素,同时因为数列是有序的,所以可以用二分查找的算法lower_bound
            }
        }
        return DP.size();
    }
};

//用到二分查找的c++STL库函数有:lower_bound()、upper_bound()、equal_range() 以及 binary_search()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值