[fb 面经] intervals sweep line

Leetcode 上的题

Merge Intervals

Insert Intervals

Meeting Rooms

Meeting RoomsII

Topcoder tutorial:

Sweep Line Algorithms

some from gitbook about sweep line problems on leetcode:

https://robinliu.gitbooks.io/leetcode/content/Sweep_Line.html

面经:

题1:

Given an array of intervals in a line consisting of start and end points[[s1,e1],[s2,e2],...] (si < ei), find any point that is covered by mostintervals.code:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Given an array of intervals in a line consisting of start and end points
 * [[s1,e1],[s2,e2],...] (si < ei), find any point that is covered by most
 * intervals.
 */
public class IntervalCover {
    public static class Interval {
        int start;
        int end;
        Interval(int start, int end) {
            this.start = start;
            this.end = end;
        }
    }
    public int getDensity(List<Interval> intervals) {
        int[] starts = new int[intervals.size()];
        int[] ends = new int[intervals.size()];
        for (int i = 0; i < starts.length; i++) {
            starts[i] = intervals.get(i).start;
            ends[i] = intervals.get(i).end;
        }
        Arrays.sort(starts);
        Arrays.sort(ends);
        int end = 0;
        int ans = 0;
        for (int i = 0; i < starts.length; i++) {
            if (starts[i] >= ends[end]) {
                end++;
            } else {
                ans = starts[i];
            }
        }
        return ans;
    }
    public static void main(String[] args) {
        // String input = "[[0,30],[5,10],[15,20]]";
        // String input = "[[7,10],[2,4]]";
        // String input = "[[5,8],[6,8]]";
        // String input = "[[13,15],[1,13]]";
        String input = "[[2,7]]";
        List<Interval> intervals = new ArrayList<Interval>();
        for (String str : input.substring(2, input.length() - 2).split("\\],\\[")) {
            String[] strs = str.split(",");
            intervals.add(new Interval(Integer.valueOf(strs[0]), Integer.valueOf(strs[1])));
        }
        System.out.println(new IntervalCover().getDensity(intervals));
    }
}

题2:

Given an array of rectangles consisting of left top and right down points[[x1,y1, x2, y2],[x3,y3,x4,y4],...] , find any point that is covered by mostrectangles.
public class IntervalD2 {
    public static class Rectangle {
        int x1;
        int y1;
        int x2;
        int y2;
        Rectangle(int x1, int y1, int x2, int y2) {
            this.x1 = x1;
            this.x2 = x2;
            this.y1 = y1;
            this.y2 = y2;
        }
        @Override
        public String toString() {
            return x1 + "|" + y1 + "|" + x2 + "|" + y2;
        }
    }
    public int[] getArea(List<Rectangle> rects) {
        Set<Integer> ys = new HashSet<Integer>();
        Map<Integer, List<Rectangle>> map = new HashMap<Integer, List<Rectangle>>();
        for (Rectangle rect : rects) {
            ys.add(rect.y1);
            ys.add(rect.y2);
            List<Rectangle> list = map.getOrDefault(rect.y1, new ArrayList<>());
            list.add(rect);
            map.put(rect.y1, list);
            list = map.getOrDefault(rect.y2, new ArrayList<>());
            list.add(rect);
            map.put(rect.y2, list);
        }
        List<Integer> yList = new ArrayList<Integer>(ys);
        Collections.sort(yList);
        PriorityQueue<Rectangle> pq = new PriorityQueue<Rectangle>((o1, o2) -> Integer.compare(o1.y2, o2.y2));
        int ans = 0;
        int ans_x = 0;
        int ans_y = 0;
        for (int y : yList) {
            List<Rectangle> list = map.get(y);
            if (list == null) {
                continue;
            }
            for (Rectangle rect : list) {
                if (rect.y1 == y) {
                    pq.add(rect);
                }
            }
            int[] starts = new int[pq.size()];
            int[] ends = new int[pq.size()];
            int counter = 0;
            System.out.println(pq.toString());
            for (Rectangle rect : pq) {
                starts[counter] = rect.x1;
                ends[counter++] = rect.x2;
            }
            Arrays.sort(starts);
            Arrays.sort(ends);
            int r = 0;
            int index = 0;
            int pos = 0;
            for (int i = 0; i < starts.length; i++) {
                if (starts[i] < ends[index]) {
                    r++;
                    pos = ends[index];
                } else {
                    index++;
                }
            }
            if (r > ans) {
                ans = r;
                ans_x = pos;
                ans_y = y;
            }
            while (!pq.isEmpty() && pq.peek().y2 <= y) {
                pq.poll();
            }
        }
        return new int[] {ans_x, ans_y, ans};
    }
    public static void main(String[] args) {
        String input = "[[1,1,4,4],[3,3,4,4],[2,4,6,6],[7,7,8,8]]";
        List<Rectangle> rects = new ArrayList<Rectangle>();
        for (String rect : input.substring(2, input.length() - 2).split("\\],\\[")) {
            String[] strs = rect.split(",");
            rects.add(new Rectangle(Integer.valueOf(strs[0]), Integer.valueOf(strs[1]), Integer.valueOf(strs[2]), Integer.valueOf(strs[3])));
        }
        System.out.println(Arrays.toString(new IntervalD2().getArea(rects)));
    }
}

题3:

Given an array of rectangles consisting of left top and right down points[[x1,y1, x2, y2],[x3,y3,x4,y4],...] , find the area covered by all these rectangles.
import com.sun.scenario.effect.impl.state.LinearConvolveKernel;

import java.util.*;

/**
 *
 */
public class IntervalD2 {
    public static class Rectangle {
        int x1;
        int y1;
        int x2;
        int y2;
        Rectangle(int x1, int y1, int x2, int y2) {
            this.x1 = x1;
            this.x2 = x2;
            this.y1 = y1;
            this.y2 = y2;
        }
        @Override
        public String toString() {
            return x1 + "|" + y1 + "|" + x2 + "|" + y2;
        }
    }
    public int getArea2(List<Rectangle> rects) {
        int ans = 0;
        Set<Integer> ys = new HashSet<Integer>();
        Map<Integer, List<Rectangle>> map = new HashMap<Integer, List<Rectangle>>();
        for (Rectangle rect : rects) {
            ys.add(rect.y1);
            ys.add(rect.y2);
            List<Rectangle> list = map.getOrDefault(rect.y1, new ArrayList<>());
            list.add(rect);
            map.put(rect.y1, list);
            list = map.getOrDefault(rect.y2, new ArrayList<>());
            list.add(rect);
            map.put(rect.y2, list);
        }
        System.out.println(map.toString());
        List<Integer> yList = new ArrayList<Integer>(ys);
        Collections.sort(yList);
        System.out.println(yList.toString());
        PriorityQueue<Rectangle> pq = new PriorityQueue<Rectangle>((o1, o2) -> Integer.compare(o1.y2, o2.y2));
        for (int i = 0; i < yList.size(); i++) {
            int y = yList.get(i);
            List<Rectangle> list = map.get(y);
            if (list == null) {
                continue;
            }
            System.out.println(pq.toString());
            if (!pq.isEmpty()) {
                int[] starts = new int[pq.size()];
                int[] ends = new int[pq.size()];
                int counter = 0;
                int deltaY = yList.get(i) - yList.get(i - 1);

                for (Rectangle rect : pq) {
                    starts[counter] = rect.x1;
                    ends[counter++] = rect.x2;
                }
                Arrays.sort(starts);
                Arrays.sort(ends);
                int a = 0;
                int b = 0;
                int r = 0;
                while (a < starts.length) {
                    if (starts[a] < ends[b]) {
                        if (r == 0) {
                            ans += (ends[b] - starts[a]) * deltaY;
                            System.out.println("ans: " + ans);
                        }
                        a++;
                        r++;
                    } else {
                        r--;
                        b++;
                    }
                }
                while (!pq.isEmpty() && pq.peek().y2 == y) {
                    pq.poll();
                }
            }

            for (Rectangle rect : list) {
                if (rect.y1 == y) {
                    pq.add(rect);
                }
            }
        }
        return ans;
    }
    public static void main(String[] args) {
        String input = "[[1,1,4,4],[3,3,4,4],[4,4,6,6],[7,7,8,8]]";
        List<Rectangle> rects = new ArrayList<Rectangle>();
        for (String rect : input.substring(2, input.length() - 2).split("\\],\\[")) {
            String[] strs = rect.split(",");
            rects.add(new Rectangle(Integer.valueOf(strs[0]), Integer.valueOf(strs[1]), Integer.valueOf(strs[2]), Integer.valueOf(strs[3])));
        }
        System.out.println(new IntervalD2().getArea2(rects));
    }
}
时间: 2024-10-20 08:19:42

[fb 面经] intervals sweep line的相关文章

Sweep Line

391. Number of Airplanes in the Sky https://www.lintcode.com/problem/number-of-airplanes-in-the-sky/description?_from=ladder&&fromId=4 思路:将起飞时间和降落时间放到同一个数组中, 标识出是起飞还是降落时间, 然后对数组排序,遍历数组即可, 碰到起飞计数器加一, 碰到降落计数器减一. 维护最大值作为答案. 注意降落优先于起飞 可通过flag标记降落为0 上升

Leetcode: Find Right Interval

Given a set of intervals, for each of the interval i, check if there exists an interval j whose start point is bigger than or equal to the end point of the interval i, which can be called that j is on the "right" of i. For any interval i, you ne

[算法]Comparison of the different algorithms for Polygon Boolean operations

Comparison of the different algorithms for  Polygon Boolean operations. Michael Leonov 1998 http://www.angusj.com/delphi/clipper.php#screenshots http://www.complex-a5.ru/polyboolean/comp.html http://www.angusj.com/delphi/clipper.php#screenshots Intro

issues about Facebook Login

在学习The complete iOS 9 Developer Course - Build 18 Apps 中的Letture134-Facebook Login,需要整合(integrate)Parse+Facebook在iOS(Xcode)中,也就是用Facebook的账户登录制作的APP(copy Tinder),然后在Parse中记录账户的相关信息,而不用手动建立.登陆成功之后在后台返回账户的名称等public_profile. 此Lecture算是至今最难的一节,因为1.Parse的

ACM1558两线段相交判断和并查集

Segment set Problem Description A segment and all segments which are connected with it compose a segment set. The size of a segment set is the number of segments in it. The problem is to find the size of some segment set. Input In the first line ther

POJ2680(动态规划,大数)

Computer Transformation Time Limit: 1000MS   Memory Limit: 65536K Total Submissions: 4548   Accepted: 1731 Description A sequence consisting of one digit, the number 1 is initially written into a computer. At each successive time step, the computer s

CartO

Carto documentation The following is a list of properties provided in CartoCSS that you can apply to map elements. All elements image-filters functions agg-stack-blurembossblurgraysobeledge-detectx-gradienty-gradientinvertsharpencolor-blind-protanope

ArcGIS空间分析工具

1. 3D分析 1.1. 3D Features toolset 工具 工具 描述 3D Features toolset (3D 要素工具集) Add Z Information 添加 Z 信息 添加关于具有 Z 值的要素类中的要素的高程属性的信息. Buffer 3D 3D 缓冲 围绕点或线创建三维缓冲区以生成球形或圆柱形的多面体要素. Difference 3D 3D 差异 消除目标要素类中部分与减法要素类中闭合的多面体要素体积重叠的多面体要素. Enclose Multipatch 封闭

2M线实验配置总结

2M线实验配置总结 1.查看路由器接口 R1#show ip int br *Mar  1 00:26:28.868: %SYS-5-CONFIG_I: Configured from console by consolep  int br Interface                  IP-Address      OK? Method Status                Protocol Ethernet0/0                unassigned      Y