Divide and Conquer

1

2 218 The Skyline Problem     最大堆   遍历节点

    public List<int[]> getSkyline(int[][] buildings) {
        List<int[]> res = new ArrayList<>();
        List<int[]> point = new ArrayList<>();
        for (int i = 0; i < buildings.length; i++)
        {
            point.add(new int[]{buildings[i][0], buildings[i][2]});
            point.add(new int[]{buildings[i][1], -buildings[i][2]});
        }
        Collections.sort(point, (a,b)-> {
            if (a[0] != b[0]) return a[0] - b[0];
            return b[1] - a[1];});
        PriorityQueue<Integer> maxheap = new PriorityQueue<>((a,b)->(b - a));
        int cur = 0, pre = 0;
        for (int i = 0; i < point.size(); i++)
        {
            int[] b = point.get(i);
            if (b[1] > 0)
            {
                maxheap.add(b[1]);
                cur = maxheap.peek();
            }
            else
            {
                maxheap.remove(-b[1]);
                cur = maxheap.peek() == null ? 0 : maxheap.peek();
            }
            if (pre != cur)
            {
                res.add(new int[]{b[0], cur});
                pre = cur;
            }
        }
        return res;
    }
View Code

 3  241 Different Ways to Add Parentheses   找符号,分开

    public List<Integer> diffWaysToCompute(String input) {
        List<Integer> res = new LinkedList<>();
        for (int i = 0; i < input.length(); i++)
        {
            char c = input.charAt(i);
            if (c == '+' || c == '-' || c == '*')
            {
                String a = input.substring(0, i);
                String b = input.substring(i+1);
                List<Integer> a1 = diffWaysToCompute(a);
                List<Integer> b1 = diffWaysToCompute(b);
                for (int x : a1)
                {
                    for (int y : b1)
                    {
                        if (c == '+')
                        {
                            res.add(x + y);
                        }
                        else if (c == '-')
                        {
                            res.add(x - y);
                        }
                        else if (c == '*')
                        {
                            res.add(x * y);
                        }
                    }
                }
            }
        }
        if (res.size() == 0) res.add(Integer.valueOf(input));
        return res;
    }
View Code
原文地址:https://www.cnblogs.com/whesuanfa/p/6817014.html