Leetcode Longest Increasing Subsequence
2015-12-05 10:45
507 查看
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; }
相关文章推荐
- 动易2006序列号破解算法公布
- Ruby实现的矩阵连乘算法
- C#插入法排序算法实例分析
- 超大数据量存储常用数据库分表分库算法总结
- C#数据结构与算法揭秘二
- C#冒泡法排序算法实例分析
- 算法练习之从String.indexOf的模拟实现开始
- C#算法之关于大牛生小牛的问题
- C#实现的算24点游戏算法实例分析
- c语言实现的带通配符匹配算法
- 浅析STL中的常用算法
- 算法之排列算法与组合算法详解
- C++实现一维向量旋转算法
- Ruby实现的合并排序算法
- C#折半插入排序算法实现方法
- C++动态规划之最长公子序列实例
- C++动态规划之背包问题解决方法
- 基于C++实现的各种内部排序算法汇总
- C++线性时间的排序算法分析
- C++实现汉诺塔算法经典实例