Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //https://www.youtube.com/watch?v=tAhT2qDgEyI
- /*
- Step 1: We will sort the array first on the basis of x then y.
- Step 2: so the first element will always be in fence because it's x and y both is less than others or one is same other is less.
- We will include first 2 points in the Uppr_tree eg. A and B so we will traverse the sorted points from 3 and if slope
- of A to C is greater than A to B then B should be removed else B should also be there and C should also be included.
- In other language,if new point is lying in left of previous two points eg. line from A to B then add C else remove B.
- Remove B until the size of rTree is not equal to 1 because first point will always be there because it's x and y is
- smaller than other points
- step 3: step 2 for finding the Upper HULL ie. the points we will see from top
- so find the lower hull.Do same from last points
- step4:merge upper and lower hull and remove the duplicate points
- */
- class Solution {
- public:
- int checkrightleft(vector<int> A, vector<int> B, vector<int> C) { //((y3-y1/x3-x1) - (y2-y1)/(x2-x1)) if > 0
- //means slope of AC is greater
- return ((B[0] - A[0]) * (C[1] - A[1])) - ((B[1] - A[1]) * (C[0] - A[0]));
- }
- vector<vector<int>> outerTrees(vector<vector<int>>& trees) {
- if (trees.size() <= 3) return trees;
- sort(trees.begin(), trees.end());
- // Upper HULL
- vector<vector<int>> Uppr_tree;
- Uppr_tree.push_back(trees[0]);
- Uppr_tree.push_back(trees[1]);
- for (int i = 2; i < trees.size(); i++) {
- int ls= Uppr_tree.size();
- while (Uppr_tree.size() >= 2 && checkrightleft(Uppr_tree[ls-2], Uppr_tree[ls-1], trees[i]) > 0) {
- Uppr_tree.pop_back();
- ls--;
- }
- Uppr_tree.push_back(trees[i]);
- }
- // Lower HULL
- vector<vector<int>> rTrees;
- rTrees.push_back(trees[trees.size() - 1]);
- rTrees.push_back(trees[trees.size() - 2]);
- for (int i = trees.size() - 3; i >= 0; --i) {
- int rs = rTrees.size();
- while (rTrees.size() >= 2 && checkrightleft(rTrees[rs-2], rTrees[rs-1], trees[i]) > 0) {
- rTrees.pop_back();
- rs--;
- }
- rTrees.push_back(trees[i]);
- }
- vector<vector<int>> answer(Uppr_tree.size()+rTrees.size()); //creating an array of combined size
- merge(Uppr_tree.begin(), //merging the array
- Uppr_tree.end(),
- rTrees.begin(),
- rTrees.end(),
- answer.begin());
- sort(answer.begin(), answer.end()); //sorting the array
- answer.erase(std::unique(answer.begin(), answer.end()), answer.end()); //removing common elements
- return answer;
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement