8.14 作业帮真题 个人记录
今天的作业帮可能主要考的是输入输出。。
第一题 两数之和
#include <iostream> #include <vector> #include <sstream> using namespace std; int main(){ string str; cin >> str; // 去除 [ ] str = str.substr(1); str.pop_back(); int target; cin >> target; vector<int> arr; string tem; stringstream ss(str); while(getline(ss, tem, ',')) arr.push_back(stoi(tem)); int left = 0, right = arr.size()-1; while( left < right ){ if(arr[left] + arr[right] == target) cout << arr[left++] << "," << arr[right--] << endl; else if(arr[left] + arr[right] > target) right--; else left++; } // 把数组遍历了一遍, 复杂度为 O(N) return 0; }
第二题 字符串反转
#include <iostream> using namespace std; int main(){ string str; getline(cin, str); int l = 0, r = str.size()-1; while( l < r ) swap(str[l++], str[r--]); cout << str << endl; return 0; }
第三题 最长连续序列的长度
#include <iostream> #include <vector> #include <sstream> #include <unordered_map> using namespace std; int getRes(vector<int>& nums){ if(nums.size() < 2)return nums.size(); unordered_map<int, int> hash; int res = 1; for(auto it:nums){ // 避免重复 if(hash[it] == 0){ // 每次根据相连的值去更新自己的值 int l = hash[it-1], r = hash[it+1]; hash[it] = l+r+1; hash[it-l] = l+r+1; hash[it+r] = l+r+1; res = max(res,hash[it]); } } return res; } int main(){ string str; getline(cin, str); vector<int> arr; int ind = 0; while(++ind < str.size()){ if(str[ind] >= '0' && str[ind] <= '9'){ int num = str[ind++]-'0'; while(str[ind] >= '0' && str[ind] <= '9') num = num*10 + str[ind++]-'0'; arr.push_back(num); } } int res = getRes(arr); cout << res << endl; return 0; }#作业帮##笔试题目##笔经#