Data Structure (Stack+Heap+TreeMap+Deque)

Stack

735. Asteroid Collision

We are given an array asteroids of integers representing asteroids in a row.

For each asteroid, the absolute value represents its size, and the sign represents its direction (positive meaning right, negative meaning left). Each asteroid moves at the same speed.

Find out the state of the asteroids after all collisions. If two asteroids meet, the smaller one will explode. If both are the same size, both will explode. Two asteroids moving in the same direction will never meet.

陨石撞击,用栈模拟,关键是分析出来有几种情况。最后栈的情况一定是 - - - + + +。分析清楚栈顶元素的正负和当前元素的正负就能作出题。

    public int[] asteroidCollision(int[] asteroids) {
        // [- - - + + +]
        if (asteroids == null) return new int[0];
        Stack<Integer> stack = new Stack<>();
        for (int num : asteroids) {

            // peek element is +, num is -
            while (!stack.isEmpty() && stack.peek() > 0 && stack.peek() < -num) {
                stack.pop();
            }
            //  peek is negative,
            if (stack.isEmpty() || num > 0 || stack.peek() < 0) {
                stack.push(num);
            }
            if (num < 0 && stack.peek() == -num) {
                stack.pop();
            }
            // skip
       
        }
        int[] res = new int[stack.size()];
        int j = stack.size() - 1;
        while (!stack.isEmpty()) {
            res[j--] = stack.pop();
            
        }
        return res;
    }

341. Flatten Nested List Iterator

In design

20. Valid Parentheses

Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.

    public boolean isValid(String s) {
        Stack<Character> stack = new Stack<Character>();
        for (char c : s.toCharArray()) {
            if (c == '(')
                stack.push(')');
            else if (c == '{')
                stack.push('}');
            else if (c == '[')
                stack.push(']');
            else if (stack.isEmpty() || stack.pop() != c)
                return false;
        }
        return stack.isEmpty();   
    }

227. Basic Calculator II

"3+2*2" = 7
" 3/2 " = 1
" 3+5 / 2 " = 5

用stack保存扫过的每一个数,遇到乘法pop出来,算过后再push回去。
这么做会带来一个问题:如何处理最后一个数,如何初始化lastopreator。

    public int calculate(String s) {
        if (s == null || s.length() == 0) {
            return 0;
        }
        // 存每个数
        Stack<Integer> stack = new Stack<>();
        String temp = "";
        // 初始化为+没想到,也是为了算最后一个数
        char last_operator = '+';
        // how to calculate the last number;
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (Character.isDigit(c)) {
                temp = temp + c;
            } 
            if (c != ' ' && !Character.isDigit(c) || i == s.length() - 1) {
                int val = Integer.parseInt(temp);
                temp = ""; // clear
        
                if (last_operator == '+') {
                    stack.push(val);
                } else if (last_operator == '-') {
                    stack.push(-val)''
                } else if (last_operator == '*') {
                    stack.push(stack.pop() * val);
                } else {
                    stack.push(stack.pop() / val);                    
                }
                last_operator = c;
            }
        }
        int res = 0;
        for (!stack.isEmpty()) {
            res += stack.pop();
        }
        return res;
    }

Proprity Queue

        // 从大到小排序
        Comparator<Task> comparator = (t1, t2) -> t2.count - t1.count;
PriorityQueue<ListNode> queue= new PriorityQueue<ListNode>(lists.size(),new Comparator<ListNode>(){
            @Override
            public int compare(ListNode o1,ListNode o2){
                if (o1.val<o2.val)
                    return -1;
                else if (o1.val==o2.val)
                    return 0;
                else 
                    return 1;
            }
        });

295. Find Median from Data Stream

[2,3,4] , the median is 3

[2,3], the median is (2 + 3) / 2 = 2.5

Design a data structure that supports the following two operations:

void addNum(int num) - Add a integer number from the data stream to the data structure.
double findMedian() - Return the median of all elements so far.
For example:

addNum(1)
addNum(2)
findMedian() -> 1.5
addNum(3)
findMedian() -> 2

用两个heap去做,一个最大堆(存数组中小的那部分)一个最小堆(存数组中大的那部分),两个堆里元素的数量最多相差1。进来元素先加入最小堆,再把最小值pop出来加入最大堆。这时候如果最大堆的元素个数多于最小堆,就pop出最大值加入最小堆。想到一分为二的处理数组。

class MedianFinder {

   /** initialize your data structure here. */
   PriorityQueue<Integer> max; // a max heap storing smaller half
   PriorityQueue<Integer> min; // a min head storing larger half
   public MedianFinder() {
       min = new PriorityQueue<>();
       max = new PriorityQueue<>(Collections.reverseOrder());
   }
   
   public void addNum(int num) {
       min.offer(num);
       max.offer(min.poll());
       // shift to maintain the size difference no more than 1
       if (max.size() > min.size()) {
           min.offer(max.poll());
       }
   }
   
   public double findMedian() {
       if (min.size() == max.size()) {
           return (max.peek() + min.peek()) / 2.0;
       } else {
           return min.peek();
       }
   }
}

621. Task Scheduler

However, there is a non-negative cooling interval n that means between two same tasks, there must be at least n intervals that CPU are doing different tasks or just be idle.
You need to return the least number of intervals the CPU will take to finish all the given tasks.
Example 1:
Input: tasks = ["A","A","A","B","B","B"], n = 2
Output: 8
Explanation: A -> B -> idle -> A -> B -> idle -> A -> B.

算个数和给出真正的顺序是有差别的,不必纠结于先A还是先B,开始想复杂了。实际上每个坑有n+1个元素,从频率高到低从pq里poll出来填进坑里,如果pq里没任务了但计数器还没到n+1,就说明需要加idle。tempList的task如果freq大于1,再丢回pq

public class Solution {
    public int leastInterval(char[] tasks, int n) {
        // construct a priority queue
        Comparator<Task> comparator = (t1, t2) -> t2.count - t1.count;
        PriorityQueue<Task> queue = new PriorityQueue<>(tasks.length, comparator);
        int[] temp = new int[26];
        for (char c : tasks) {
            temp[c - 'A'] += 1;
        }
        for (int i = 0; i < temp.length; i++) {
            if (temp[i] > 0) {
                Task task = new Task((char)(i + 'A'), temp[i]);
                queue.add(task);                
            }
        }
        
        int res = 0;
        while (!queue.isEmpty()) {
            int k = n + 1;
            List<Task> tempList = new ArrayList<>();
            while (k > 0 && !queue.isEmpty()) {
                Task t = queue.poll();
                t.count = t.count - 1;
                k--;
                res++;
            }
            // copy
            for (Task t1 : tempList) {
                if (t1.count > 0)
                    queue.add(t1);
            }
            if (queue.isEmpty()) {
                break;
            }
            res += k;
            
        }
        return res;
    }
}
class Task {
    char name;
    int count;
    public Task(char name, int count) {
        this.name = name;
        this.count = count;
    }
}

Deque

272. Closest Binary Search Tree Value II

Given a non-empty binary search tree and a target value, find k values in the BST that are closest to the target.

Note:
Given target value is a floating point.
You may assume k is always valid, that is: k ≤ total nodes.
You are guaranteed to have only one unique set of k values in the BST that are closest to the target.
Follow up:
Assume that the BST is balanced, could you solve it in less than O(n) runtime (where n = total nodes)?

BST自然想到中序遍历,中序递归方便。根据题意需要维护一个size固定的数据结构,当新进来的值比数据结构里的值更满足条件时,removeFirst,所以想到用deque。(peekFirst, removeFirst)
注意的是linkedlist声明不能用范型。
注意else里的return,如果当前值都不能加入deque里,那么后面的值差的更多,更不能加入deque

class Solution {
    public List<Integer> closestKValues(TreeNode root, double target, int k) {
        // traverse the tree in in-order recursively
        LinkedList<Integer> res = new LinkedList<>();
        helper(root, target, k, res);
        return res;
    }
    public void helper(TreeNode root, double target, int k, LinkedList<Integer> res) {
        if (root == null) {
            return;
        }
        helper(root.left, target, k, res);
        // check the size of res
        if (res.size() == k) {
            if (Math.abs(root.val - target) < Math.abs(target - res.peekFirst())) {
                res.removeFirst();
            } 
            else {
                
                return;
            }
        }
        res.add(root.val);
        helper(root.right, target, k, res);
    }
}

239. Sliding Window Maximum

Given nums = [1,3,-1,-3,5,3,6,7], and k = 3.
Therefore, return the max sliding window as [3,3,5,5,6,7].
Find max value of each sliding window

用双端队列,LinkedList实现
队列里存index,不存值,
每进来一个新值,1)看是不是要poll出最老的元素 2)进来的新值如果比之前的值大,pollLast,poll到deque为空或者碰到比它大的值

class Solution {
    public int[] maxSlidingWindow(int[] nums, int k) {
        int n = nums.length;
        if (n == 0) {
            return nums;
        }
        int[] result = new int[n - k + 1];
        LinkedList<Integer> dq = new LinkedList<>();
        for (int i = 0; i < n; i++) {
            // peek, poll针对队头(最早进入的元素)
            if (!dq.isEmpty() && dq.peek() < i - k + 1) {
                dq.poll();
            }
            while (!dq.isEmpty() && nums[i] >= nums[dq.peekLast()]) {
                dq.pollLast();
            }
            dq.offer(i);
            if (i - k + 1 >= 0) {
                result[i - k + 1] = nums[dq.peek()];
            }
        }
        return result;
    }
}

TreeMap

Treemap是有序的hashmap,基于red black tree实现,根据key排序。
get,put,containsKey是long(n)

  • Entry
    TreeMap的 firstEntry()、 lastEntry()、 lowerEntry()、 higherEntry()、 floorEntry()、 ceilingEntry()、 pollFirstEntry() 、 pollLastEntry()
  • Key
    firstKey()、lastKey()、lowerKey()、higherKey()、floorKey()、ceilingKey()
    floorKey(k1)是找比k1小于等于的里面最大的key

https://www.cnblogs.com/skywang12345/p/3310928.html

729. My Calendar I

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 217,826评论 6 506
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,968评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,234评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,562评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,611评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,482评论 1 302
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,271评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,166评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,608评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,814评论 3 336
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,926评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,644评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,249评论 3 329
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,866评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,991评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,063评论 3 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,871评论 2 354

推荐阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 9,497评论 0 23
  • 今天,妹妹生病了,我一回家就看见了她躺在床上,我吃完饭就过去看妹妹,我看她非常难受,我就拿起了一本故事书给她讲故...
    谷佳琦阅读 326评论 1 1
  • 我要的新鮮感 不是和不同的人吃同樣的早餐 (呵 不重樣的也不行) 而是和同一個人吃不同的早餐 (重樣的卻不行) ...
    Hero啾啾啾阅读 144评论 0 1
  • Docker基本概念 Docker镜像 Docker 镜像是一个特殊的文件系统,除了提供容器运行时所需的程序、库、...
    sunny4handsome阅读 168评论 0 0
  • 题外话 先推荐一个安卓动画解决方案,如果公司的设计师可以使用AE设计APP内需求的动画效果(配合bodymovin...
    bluesfantasy阅读 9,333评论 1 5