LeetCode 480. 滑動視窗中位數
阿新 • • 發佈:2021-02-04
技術標籤:刷題
難度:困難。
感覺沒有昨天的難呀。這個有點思路。
用一個大小為k的陣列有序的儲存每個視窗的數,每次視窗移動更新一次。
使用二分法刪除和插入數字。
正確解法:
class Solution {
void update_vector(vector<int>& nums, int del_num, int add_num){
int n = nums.size();
int left = 0, right = n - 1, mid = 0;
while(left <= right){
mid = (left + right) / 2;
if(nums[mid] < del_num){
left = mid + 1;
}
else if(nums[mid] > del_num){
right = mid - 1;
}
else{
nums.erase(nums.begin() + mid);
break;
}
}
left = 0, right = n - 2;
while(left <= right){
mid = (left + right) / 2;
if(nums[mid] < add_num){
left = mid + 1;
}
else if(nums[mid] > add_num){
right = mid - 1;
}
else {
right = mid;
break;
}
}
nums.insert(nums.begin() + right + 1, add_num);
}
public:
vector<double> medianSlidingWindow(vector<int>& nums, int k) {
vector<double> ans;
int n = nums.size();
if(k == 1){
for(int i = 0; i < n; i++){
ans.push_back(nums[i]);
}
return ans;
}
vector<int> orderd_array(k);
for(int i = 0; i < k; i++){
orderd_array[i] = nums[i];
}
sort(orderd_array.begin(), orderd_array.end());
int left = 0, right = k - 1;
double temp1 = 0, temp2 = 0;
if(k % 2){
ans.push_back(orderd_array[k / 2]);
}
else{
temp1 = orderd_array[k / 2 - 1];
temp2 = orderd_array[k / 2];
ans.push_back((temp1 + temp2) / 2.0);
}
while(right < n - 1){
left++;
right++;
update_vector(orderd_array, nums[left - 1], nums[right]);
if(k % 2){
ans.push_back(orderd_array[k / 2]);
}
else{
temp1 = orderd_array[k / 2 - 1];
temp2 = orderd_array[k / 2];
ans.push_back((temp1 + temp2) / 2.0);
}
}
return ans;
}
};