正文索引 [隐藏]
T1重新排列数组
签到题,按题意模拟就行
class Solution { public: vector<int> shuffle(vector<int>& nums, int n) { vector<int> ans; for(int i = 0; i < n; i++) { ans.push_back(nums[i]); ans.push_back(nums[n+i]); } return ans; } };
T2 数组中的 k 个最强值
就是根据题目要求重新定义排序规则,在排序后取前k项即是答案
int m; bool cmp(int a, int b) { if(abs(a - m) != abs(b - m)) return abs(a - m) > abs(b - m); return a > b; } class Solution { public: vector<int> getStrongest(vector<int>& arr, int k) { int n = arr.size(); sort(arr.begin(), arr.end()); m = arr[(n-1)/2]; sort(arr.begin(), arr.end(), cmp); vector<int> ans; for(int i = 0; i < k; i++) ans.push_back(arr[i]); return ans; } };
T3 设计浏览器历史记录
用数组模拟操作,题意读仔细就行了。
class BrowserHistory { public: string web[5000]; int now = -1; int size = -1; BrowserHistory(string homepage) { visit(homepage); } void visit(string url) { now++; web[now] = url; size = now; } string back(int steps) { if(now - steps < 0) { now = 0; return web[now]; } else { now -= steps; return web[now]; } } string forward(int steps) { if(now + steps > size) now = size; else now += steps; return web[now]; } }; /** * Your BrowserHistory object will be instantiated and called as such: * BrowserHistory* obj = new BrowserHistory(homepage); * obj->visit(url); * string param_2 = obj->back(steps); * string param_3 = obj->forward(steps); */
评论
还没有任何评论,你来说两句吧!