NC95. 数组中的最长连续子序列
描述
示例1
输入:
[100,4,200,1,3,2]
输出:
4
示例2
输入:
[1,1,1]
输出:
1
C++ 解法, 执行用时: 17ms, 内存消耗: 3756KB, 提交时间: 2021-09-15
static const auto io_sync_off = [] (){ std::ios::sync_with_stdio(false); std::cin.tie(nullptr); return nullptr; }(); class Solution { public: /** * max increasing subsequence * @param arr int整型vector the array * @return int整型 */ int MLS(vector<int>& arr) { // write code here int n = arr.size(); sort(arr.begin(), arr.end()); int sum = 1; int maxlen = 1; //int i = 1; for(int i=1; i<n; i++){ if(arr[i] == arr[i-1]) continue; if(arr[i-1]+1 == arr[i]) sum++; else sum = 1; maxlen = max(sum,maxlen); //i++; } return maxlen; } };
C++ 解法, 执行用时: 21ms, 内存消耗: 3720KB, 提交时间: 2021-06-18
static const auto io_sync_off = []() { // turn off sync std::ios::sync_with_stdio(false); // untie in/out streams std::cin.tie(nullptr); return nullptr; }(); class Solution { public: /** * max increasing subsequence * @param arr int整型vector the array * @return int整型 */ int MLS(vector<int>& arr) { // write code here sort(arr.begin(), arr.end()); int i_end = arr.size()-1, cnt = 1, max = 1; for(int i=0; i<i_end; i++){ if(arr[i] == arr[ i+1 ]) continue; if(arr[i]+1 == arr[ i+1 ]){ if(++cnt > max) max = cnt; continue; } cnt = 1; } return max; } };
C++ 解法, 执行用时: 21ms, 内存消耗: 4732KB, 提交时间: 2021-06-26
static const auto io_sync_off = []() { // turn off sync std::ios::sync_with_stdio(false); // untie in/out streams std::cin.tie(nullptr); return nullptr; }(); class Solution { public: /** * max increasing subsequence * @param arr int整型vector the array * @return int整型 */ int MLS(vector<int>& arr) { // write code here sort(arr.begin(), arr.end()); int max = 1; int count = 1; for (int i = 1; i < arr.size();i++) { if (arr[i-1] == arr[i]) { continue; } else if (arr[i-1] + 1 == arr[i]) { count++; if (count > max) max = count; } else { count = 1; } } return max; } };
C++ 解法, 执行用时: 22ms, 内存消耗: 3756KB, 提交时间: 2021-08-24
static const auto io_sync_off = []() { // turn off sync std::ios::sync_with_stdio(false); // untie in/out streams std::cin.tie(nullptr); return nullptr; }(); class Solution { public: /** * max increasing subsequence * @param arr int整型vector the array * @return int整型 */ int MLS(vector<int>& arr) { // write code here int res=1; sort(arr.begin(), arr.end()); int tmp=1; for(int i=0;i<arr.size()-1;i++) { if(arr[i]+1==arr[i+1]) tmp++; else if(arr[i]==arr[i+1]) continue; else tmp=1; res=max(tmp, res); } return res; } };
C++ 解法, 执行用时: 22ms, 内存消耗: 3876KB, 提交时间: 2022-05-08
static const auto io_sync_off = [] () { std::ios::sync_with_stdio(false); std::cin.tie(nullptr); return nullptr; } (); class Solution { public: int MLS(vector<int>& arr) { int n = arr.size(); sort(arr.begin(), arr.end()); int sum = 1; int maxlen = 1; for (int i = 1; i < n; i++) { if (arr[i] == arr[i - 1]) continue; if (arr[i - 1] + 1 == arr[i]) sum++; else sum = 1; maxlen = max(sum, maxlen); } return maxlen; } };