LeetCode218. The Skyline Problem分治法
来源:互联网 发布:为了提高软件质量 编辑:程序博客网 时间:2024/06/07 05:05
题意:轮廓问题,不好描述。
首先怎么分:
- 不停对半分
- 停止条件1:为空时,直接返回空
- 停止条件2:大小为1时,直接返回左上角点和右下角点。
那么怎么合并?
- 维护两个变量:l,r l为左半部分当前位置,r为右半部分当前位置
- 维护两个变量:h1,h2 h1表示左半部分当前位置高度,h2表示右半部分档期位置高度
- 如果当前位置左半部分横坐标更小,就更新h1,从左半部分选元素;
- 如果当前位置右半部分横坐标更小,就更新h2,从右半部分选元素;
- 如果一样大,就更新h1,h2,从左(或右)半部分选元素
- 当向结果中插入点时,只有和结果中最后一个点高度不同的点才能插入到结果里,且一直使用高度max(h1,h2)。
- 当某一部分全部访问过后,就将另一部分(和结果中最后一个点高度不同的点)直接插入结果里。
#include <algorithm>class Solution {public: vector<pair<int, int>> getSkyline(vector<vector<int>>& buildings) { if(buildings.empty()) return vector<pair<int, int> >(); if(buildings.size()==1){ vector<pair<int, int> > vec; vec.push_back(pair<int,int>(buildings[0][0],buildings[0][2])); vec.push_back(pair<int,int>(buildings[0][1],0)); return vec; } int mid=buildings.size()/2; vector<vector<int>> bl(buildings.begin(),buildings.begin()+mid); vector<vector<int>> br(buildings.begin()+mid,buildings.end()); vector<pair<int, int>> left=getSkyline(bl); vector<pair<int, int>> right=getSkyline(br); return merge(left,right); } vector<pair<int, int>> merge(vector<pair<int, int>>& left, vector<pair<int, int>>& right){ int h1=0,h2=0; int l=0,r=0; vector<pair<int, int>> ans; while(l<left.size()&&r<right.size()){ if(left[l].first<right[r].first){ h1=left[l].second; if(ans.empty()||ans.back().second!=max(h1,h2)) ans.push_back(pair<int,int>(left[l].first,max(h1,h2))); l++; } else if(left[l].first>right[r].first){ h2=right[r].second; if(ans.empty()||ans.back().second!=max(h1,h2)) ans.push_back(pair<int,int>(right[r].first,max(h1,h2))); r++; } else{ h1=left[l].second; h2=right[r].second; if(ans.empty()||ans.back().second!=max(h1,h2)) ans.push_back(pair<int,int>(left[l].first,max(h1,h2))); l++,r++; } } for(int i=l;i<left.size();++i) if(ans.empty()||ans.back().second!=left[i].second) ans.push_back(left[i]); for(int i=r;i<right.size();++i) if(ans.empty()||ans.back().second!=right[i].second) ans.push_back(right[i]); return ans; }};
0 0
- LeetCode218. The Skyline Problem分治法
- LeetCode218:The Skyline Problem
- LeetCode 218. The Skyline Problem--Divide and Conquer(分治法)
- 105 - The Skyline Problem
- leetcode - The Skyline Problem
- The Skyline Problem
- The Skyline Problem
- The Skyline Problem
- LeetCode - The Skyline Problem
- leetcode:the skyline problem
- The Skyline Problem -- leetcode
- Leetcode -- The Skyline Problem
- 218 .The Skyline Problem
- The Skyline Problem
- The Skyline Problem
- The Skyline Problem
- The Skyline Problem
- The Skyline Problem
- linux命令详解:md5sum命令
- HTML 第三章
- 安全加密算法与数据签名总结(3)
- Linux环境下完成远程系统迁移
- 使用golang快速开发微信公众平台(三):定制菜单
- LeetCode218. The Skyline Problem分治法
- 算法积累_java_插入,选择,冒泡,快速排序
- MFC的Format函数
- IE6兼容性之微型盒子(小于12px)
- wk5 350. Intersection of Two Arrays II
- 有赞APP IM SDK 组件架构设计
- 设计模式复习笔记 (7)创建型模式:单例模式
- 各大IT技术博客排行榜
- SLF4J 的几种实际应用模式--:SLF4J+Log4J 与 SLF4J+LogBack