Leetcode Longest Increasing Subsequence

Leetcode Longest Increasing Subsequence,本算法主要集中了动态规划和二分搜索,算法复杂度为o(n logn),相关代码如下:

#include<iostream>
#include<vector>

/* There is some tricks in this algorithm. I am inspired by others.
 * The core philosophy of the algorithm is dynamic and binary search.
 * We used the end variable recorde the max length current, and each
 * element in the [0..end] can be substitute by others which have the
 * some order as the correspond one.
 */
using namespace std;
class Solution {
public:
    int lengthOfLIS(vector<int>& nums) {
        int len = nums.size();
        if (len == 0) {
            return 0;
        }
        vector<int> recoder(len, 1);
        int end = -1;
        int tmp = 0;
        for (int i = 0; i < len; i ++) {
            // append the element to the end of substitute the correspond
            if (end < 0 || nums[i] > nums[end]) {
                nums[++ end] = nums[i];
            } else if ((tmp = binarySearch(i, nums, end)) < 0) {
                nums[- tmp - 1] = nums[i];
            }
        }
        return end + 1;
    }
    // Binary search, which reture the opposite number of the correspond
    // position.
    int binarySearch(int pos, vector<int>& nums, int end) {
        int num = nums[pos];
        int low = 0;
        int high = end;
        int mid;
        while (1) {
            if (high - low <= 1) {
                if (nums[pos] < nums[low]) {
                    return - low - 1;
                } else if (nums[pos] == nums[low]) {
                    return low;
                } else if (nums[pos] < nums[high]) {
                    return - high - 1;
                } else if (nums[pos] == nums[high]) {
                    return high;
                } else {
                    return - high - 2;
                }
            }
            mid = (high + low) / 2;
            if (nums[mid] == nums[pos]) {
                return mid;
            } else if (nums[mid] > nums[pos]) {
                high = mid - 1;
            } else {
                low = mid + 1;
            }
        }
    }
};

// Sample input: ./a.out argv1 argv2
int main(int argc, char* argv[]) {
    Solution so;
    vector<int> nums;
    for (int i = 1; i < argc; i ++) {
        nums.push_back(atoi(argv[i]));
    }
    int re = so.lengthOfLIS(nums);
    cout<<"result: "<<re<<endl;
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值