1. 程式人生 > 其它 >for迴圈和range()函式的使用舉例

for迴圈和range()函式的使用舉例

技術標籤:leetcodeleetcodec++

class Solution {
public:
vector<double> medianSlidingWindow(vector<int>& nums, int k)
{
    vector<double>res;
    for(int i=0;i<nums.size()-k+1;i++)
    {
        vector<int>cur(nums.begin()+i,nums.begin()+i+k);
        sort(cur.begin(),cur.
end()); if(k%2==0) { double temp=(cur[k/2]*1.0+cur[k/2-1]*1.0)/2; res.push_back(temp); } else { res.push_back(cur[k/2]); } } return res; } };

我的思路不出意外的超時了orz在這裡插入圖片描述然後就開始題解,看看大佬們的做法

class Solution {
public:
    vector<
double> medianSlidingWindow(vector<int>& nums, int k) { vector<double> res; multiset<double> st; for (int i = 0; i < nums.size(); ++i) { if (st.size() >= k) st.erase(st.find(nums[i - k])); st.insert(nums[i]); if
(i >= k - 1) { auto mid = st.begin(); std::advance(mid, k / 2);//講指標後移k/2個單位 res.push_back((*mid + *prev(mid, (1 - k % 2))) / 2);//得到中位數 } } return res; } };

又雙叒叕蹦出來一個新的資料結構orz,上述方法為[leetcode上負雪明燭]方法(https://leetcode-cn.com/problems/sliding-window-median/solution/xuan-ze-he-gua-de-shu-ju-jie-gou-zhe-ti-muyt4/)