[小米OJ] 4. 最长连续数列
生活随笔
收集整理的這篇文章主要介紹了
[小米OJ] 4. 最长连续数列
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
思路:
時間限制為O(n),即不能使用先排序后尋找的方法。
這里利用哈希表查詢插入復雜度都為O(1)的特性來解,利用一個哈希表來保存每一個數字以及其所在數列的長度。
遍歷每一個數字n:查詢表中是否存在n-1和n+1,若存在,則hash[n]的值為1 + hash[n-1] + hash[n+1],若不存在即是 1.
同時,為了預防相同數字多次判斷,每一次遍歷時判斷該數字在表中的value是否為0,若不為0說明已經判斷過了,跳過即可。
#include <bits/stdc++.h> using namespace std; int main() {string input;while (cin >> input){istringstream iss(input);string temp;vector<int> vec;map<int, int> mapping;int maxNum = -1;while (getline(iss, temp, ',')){vec.push_back(atoi(temp.c_str()));mapping[atoi(temp.c_str())] = 0;}for (auto c : vec){if (mapping[c] == 0){mapping[c] = 1;if (mapping.count(c - 1)){mapping[c] += mapping[c - 1];}if (mapping.count(c + 1)){mapping[c] += mapping[c + 1];}maxNum = maxNum > mapping[c] ? maxNum : mapping[c];}}cout << maxNum << endl;}return 0; }?
轉載于:https://www.cnblogs.com/ruoh3kou/p/10289642.html
總結
以上是生活随笔為你收集整理的[小米OJ] 4. 最长连续数列的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 电子印章丢失了怎么办?
- 下一篇: 前端Ajax/JS/HTML+后端Spr