第一题:6188. 按身高排序
思路:记录一下下标排序即可
class Solution { public: vector<string> sortPeople(vector<string>& names, vector<int>& heights) { int n = names.size(); vector<vector<int>> tmp(n,vector<int>(2)); for(int i = 0; i < names.size(); i++){ tmp[i][0] = heights[i]; tmp[i][1] = i; } sort(tmp.begin(),tmp.end()); vector<string> name(n); int k; for(int i = n - 1; i >=0; i--){ name[k++] = names[tmp[i][1]]; } for(int i = 0; i < n; i++) names[i] = name[i]; return names; } };
思路:其实就是找最大值的连续数组有多长
class Solution { public: int longestSubarray(vector<int>& nums) { int tmp = 0; for(int i = 0; i < nums.size(); i++) tmp = max(tmp,nums[i]); int res = 0; for(int i = 0; i < nums.size(); i++){ if(nums[i] == tmp){ int j = i; while(j < nums.size() && nums[j] == tmp) j++; res = max(res,j-i); i = j; } } return res; } };
第三题:6190. 找到所有好下标
思路:比赛时暴力做最后几个数据过不了,分别用两个数组来存储下标为i时前后非递增递减元素的个数,然后遍历找符合条件的下标即可,时间复杂度为O(n)
class Solution { public: vector<int> goodIndices(vector<int>& nums, int k) { int n = nums.size(); vector<int> x(n);//x[i]表示前i个元素有几个是非递增的 vector<int> y(n);//y[i]表示后i给元素有几个是非递减的 vector<int> res; x[0] = 1; for(int i = 0; i < n - 1; i++){ if(nums[i] >= nums[i+1]) x[i+1] = x[i]+1; else x[i+1] = 1; } y[n-1] = 1; for(int i = n - 1; i > 0; i--){ if(nums[i] >= nums[i-1]) y[i-1] = y[i]+1; else y[i-1] = 1; } for (int i = k; i < n - k; i++) if (x[i - 1] >= k && y[i + 1] >= k)res.push_back(i); return res; } };