查看: 9955| 回复: 141
跳转到指定楼层
上一主题 下一主题
收起左侧

多伦多在职每日刷题打卡也欢迎组队

全局:

注册一亩三分地论坛,查看更多干货!

您需要 登录 才可以下载或查看附件。没有帐号?注册账号

x
坐标多伦多,每日刷题打卡,争取工作日每日3道,周末5道,欢迎大家来讨论系统设计题和OOP

--另外跪求大米

上一篇:behavior question和简历问题、算法 mock求组队
下一篇:DS Analytics向 每日打卡
推荐
 楼主| zhangrz2 2019-6-4 09:52:31 | 只看该作者
全局:
307. Range Sum Query - Mutable -- binary segment tree (classic)
  1. class Node {
  2.     private int sum;
  3.     private int start;
  4.     private int end;
  5.     private Node left;
  6.     private Node right;
  7.    
  8.     public Node(int start, int end) {
  9.         this.sum = 0;
  10.         this.start = start;
  11.         this.end = end;
  12.         this.left = null;
  13.         this.right = null;
  14.     }
  15.    
  16.     public void setSum(int sum) {
  17.         this.sum = sum;
  18.     }
  19.    
  20.     public int getSum() {
  21.         return this.sum;
  22.     }
  23.    
  24.     public void setLeft(Node left) {
  25.         this.left = left;
  26.     }
  27.    
  28.     public void setRight(Node right) {
  29.         this.right = right;
  30.     }
  31.    
  32.     public int getStart() {
  33.         return this.start;
  34.     }
  35.    
  36.     public int getEnd() {
  37.         return this.end;
  38.     }
  39.    
  40.     public Node getLeft() {
  41.         return this.left;
  42.     }
  43.    
  44.     public Node getRight() {
  45.         return this.right;
  46.     }
  47. }

  48. class NumArray {
  49.    
  50.     Node head = null;
  51.    
  52.     public NumArray(int[] nums) {
  53.         head = buildTree(nums, 0, nums.length - 1);   
  54.     }
  55.    
  56.     private Node buildTree(int[] nums, int start, int end) {
  57.         if (start > end) {
  58.             return null;
  59.         }
  60.         Node head = new Node(start, end);
  61.         if (start == end) {
  62.             head.setSum(nums[start]);   
  63.         }else {
  64.             int mid = start + (end - start) / 2;
  65.             head.setLeft(buildTree(nums, start, mid));
  66.             head.setRight(buildTree(nums, mid + 1, end));
  67.             int sum = 0;
  68.             if (head.getLeft() != null) {
  69.                 sum += head.getLeft().getSum();
  70.             }
  71.             if (head.getRight() != null) {
  72.                 sum += head.getRight().getSum();
  73.             }
  74.             head.setSum(sum);
  75.         }
  76.         return head;
  77.         
  78.     }
  79.    
  80.     public void update(int i, int val) {
  81.         update(head, i, val);
  82.     }
  83.    
  84.     private void update(Node head, int index, int val) {
  85.         int start = head.getStart();
  86.         int end = head.getEnd();
  87.         if (start == end) {
  88.             head.setSum(val);
  89.             return;
  90.         }
  91.         int mid = start + (end - start) / 2;
  92.         if (index <= mid) {
  93.             update(head.getLeft(), index, val);
  94.         }else {
  95.             update(head.getRight(), index, val);
  96.         }
  97.         head.setSum(head.getLeft().getSum() + head.getRight().getSum());
  98.     }
  99.    
  100.     public int sumRange(int i, int j) {
  101.         return sumRange(head, i, j);
  102.     }
  103.    
  104.     private int sumRange(Node head, int small, int large) {
  105.         if (head.getLeft() == head.getRight()) {
  106.             return head.getSum();
  107.         }
  108.         int start = head.getStart();
  109.         int end = head.getEnd();
  110.         int mid = start + (end - start) / 2;
  111.         if (large <= mid) {
  112.             return sumRange(head.getLeft(), small, large);
  113.         }else if (small > mid) {
  114.             return sumRange(head.getRight(), small, large);
  115.         }else {
  116.             return sumRange(head.getLeft(), small, mid) + sumRange(head.getRight(), mid + 1, large);
  117.         }
  118.     }
  119. }

  120. /**
  121. * Your NumArray object will be instantiated and called as such:
  122. * NumArray obj = new NumArray(nums);
  123. * obj.update(i,val);
  124. * int param_2 = obj.sumRange(i,j);
  125. */
复制代码
回复

使用道具 举报

推荐
 楼主| zhangrz2 2019-6-13 09:55:32 | 只看该作者
全局:
本帖最后由 zhangrz2 于 2019-6-13 09:59 编辑

716. Max Stack -- two stacks

  1. class MaxStack {
  2.    
  3.     private Stack<Integer> stack;
  4.     private Stack<Integer> maxStack;
  5.    
  6.     /** initialize your data structure here. */
  7.     public MaxStack() {
  8.         this.stack = new Stack<Integer>();
  9.         this.maxStack = new Stack<Integer>();
  10.     }
  11.    
  12.     public void push(int x) {
  13.         if (stack.isEmpty()) {
  14.             maxStack.push(x);
  15.             stack.push(x);
  16.         }else {
  17.             stack.push(x);
  18.             int curMax = this.maxStack.peek();
  19.             if (x >= curMax){
  20.                 maxStack.push(x);
  21.             }else {
  22.                 maxStack.push(curMax);
  23.             }
  24.         }
  25.     }
  26.    
  27.     public int pop() {
  28.         maxStack.pop();
  29.         return stack.pop();
  30.     }
  31.    
  32.     public int top() {
  33.         return stack.peek();
  34.     }
  35.    
  36.     public int peekMax() {
  37.         return maxStack.peek();
  38.     }
  39.    
  40.     public int popMax() {
  41.         int max = peekMax();
  42.         Stack<Integer> buffer = new Stack();
  43.         while (top() != max) buffer.push(pop());
  44.         pop();
  45.         while (!buffer.isEmpty()) push(buffer.pop());
  46.         return max;
  47.     }
  48. }

  49. /**
  50. * Your MaxStack object will be instantiated and called as such:
  51. * MaxStack obj = new MaxStack();
  52. * obj.push(x);
  53. * int param_2 = obj.pop();
  54. * int param_3 = obj.top();
  55. * int param_4 = obj.peekMax();
  56. * int param_5 = obj.popMax();
  57. */
复制代码


//another brilliant solution from leetcode
class MaxStack {
    TreeMap<Integer, List<Node>> map;
    DoubleLinkedList dll;

    public MaxStack() {
        map = new TreeMap();
        dll = new DoubleLinkedList();
    }

    public void push(int x) {
        Node node = dll.add(x);
        if(!map.containsKey(x))
            map.put(x, new ArrayList<Node>());
        map.get(x).add(node);
    }

    public int pop() {
        int val = dll.pop();
        List<Node> L = map.get(val);
        L.remove(L.size() - 1);
        if (L.isEmpty()) map.remove(val);
        return val;
    }

    public int top() {
        return dll.peek();
    }

    public int peekMax() {
        return map.lastKey();
    }

    public int popMax() {
        int max = peekMax();
        List<Node> L = map.get(max);
        Node node = L.remove(L.size() - 1);
        dll.unlink(node);
        if (L.isEmpty()) map.remove(max);
        return max;
    }
}

class DoubleLinkedList {
    Node head, tail;

    public DoubleLinkedList() {
        head = new Node(0);
        tail = new Node(0);
        head.next = tail;
        tail.prev = head;
    }

    public Node add(int val) {
        Node x = new Node(val);
        x.next = tail;
        x.prev = tail.prev;
        tail.prev = tail.prev.next = x;
        return x;
    }

    public int pop() {
        return unlink(tail.prev).val;
    }

    public int peek() {
        return tail.prev.val;
    }

    public Node unlink(Node node) {
        node.prev.next = node.next;
        node.next.prev = node.prev;
        return node;
    }
}

class Node {
    int val;
    Node prev, next;
    public Node(int v) {val = v;}
}
回复

使用道具 举报

推荐
 楼主| zhangrz2 2019-5-28 09:41:52 | 只看该作者
全局:
706. Design HashMap -- linear probing

  1. class Node {
  2.     int key;
  3.     int val;
  4.     Node next;
  5.     Node prev;
  6.    
  7.     public Node(int key, int val) {
  8.         this.key = key;
  9.         this.val = val;
  10.     }
  11.    
  12.     public void setNext(Node next) {
  13.         this.next = next;
  14.     }
  15.    
  16.     public Node getNext() {
  17.         return this.next;
  18.     }
  19.    
  20.     public int getKey() {
  21.         return this.key;
  22.     }
  23.    
  24.     public int getVal() {
  25.         return this.val;
  26.     }
  27.    
  28.     public void setVal(int val) {
  29.         this.val = val;
  30.     }
  31.    
  32.     public void setPrev(Node prev) {
  33.         this.prev = prev;
  34.     }
  35.    
  36.     public Node getPrev() {
  37.         return this.prev;
  38.     }
  39. }
  40. //linear probing
  41. class MyHashMap {
  42.     Node[] nodes;
  43.     /** Initialize your data structure here. */
  44.     public MyHashMap() {
  45.         nodes = new Node[100000];
  46.     }
  47.    
  48.     /** value will always be non-negative. */
  49.     public void put(int key, int value) {
  50.         //create head node
  51.         int index = getIndex(key);
  52.         if (nodes[index] == null) {
  53.             nodes[index] = new Node(-1, -1);
  54.         }
  55.         Node target = findNode(key);
  56.         if (target == null) {
  57.             Node newNode = new Node(key, value);
  58.             Node next = nodes[index].getNext();
  59.             nodes[index].setNext(newNode);
  60.             newNode.setPrev(nodes[index]);
  61.             if (next != null) {
  62.                 next.setPrev(newNode);
  63.                 newNode.setNext(next);
  64.             }
  65.         }else {
  66.             target.setVal(value);
  67.         }
  68.     }
  69.    
  70.     /** Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key */
  71.     public int get(int key) {
  72.         Node target = findNode(key);
  73.         return target == null ? -1 : target.getVal();
  74.     }
  75.    
  76.    
  77.    
  78.     /** Removes the mapping of the specified value key if this map contains a mapping for the key */
  79.     public void remove(int key) {
  80.         Node target = findNode(key);
  81.         if (target != null) {
  82.             Node prev = target.getPrev();
  83.             Node next = target.getNext();
  84.             prev.setNext(target.getNext());
  85.             if (next != null) {
  86.                 next.setPrev(prev);
  87.             }            
  88.         }
  89.         return;
  90.     }
  91.    
  92.     private int getIndex(int key) {
  93.         return Integer.hashCode(key) % nodes.length;
  94.     }
  95.    
  96.     private Node findNode(int key) {
  97.         int index = getIndex(key);
  98.         Node leadNode = nodes[index];
  99.         if (leadNode == null) {
  100.             return null;
  101.         }
  102.         while(leadNode != null) {
  103.             if (leadNode.getKey() == key) {
  104.                 return leadNode;
  105.             }
  106.             leadNode = leadNode.getNext();
  107.         }
  108.         return null;
  109.     }
  110. }

  111. /**
  112. * Your MyHashMap object will be instantiated and called as such:
  113. * MyHashMap obj = new MyHashMap();
  114. * obj.put(key,value);
  115. * int param_2 = obj.get(key);
  116. * obj.remove(key);
  117. */
复制代码
回复

使用道具 举报

🔗
 楼主| zhangrz2 2019-5-27 02:25:24 | 只看该作者
全局:
1052. Grumpy Bookstore Owner-- sliding window

  1. class Solution {
  2.     public int maxSatisfied(int[] customers, int[] grumpy, int X) {
  3.         int satis = 0;
  4.         for (int i = 0; i < customers.length; i++) {
  5.             satis += grumpy[i] == 0 ? customers[i] : 0;
  6.         }
  7.         int window = 0;
  8.         int ans = 0;
  9.         int start = 0;
  10.         for (int i = 0; i < customers.length; i++) {
  11.             window += grumpy[i] * customers[i];
  12.             if (i >= X) {
  13.                 window -= grumpy[start] * customers[start];
  14.                 start++;
  15.             }
  16.             ans = Math.max(ans, window);
  17.         }
  18.         
  19.         return ans + satis;
  20.     }
  21. }
复制代码
回复

使用道具 举报

🔗
 楼主| zhangrz2 2019-5-27 02:50:14 | 只看该作者
全局:
1054. Distant Barcodes -- Heap(PriorityQueue)
  1. class Solution {
  2.     public int[] rearrangeBarcodes(int[] barcodes) {
  3.         int[] ans = new int[barcodes.length];
  4.         Map<Integer, Integer> count = new HashMap<>();
  5.         for (int barcode : barcodes) {
  6.             count.put(barcode, count.getOrDefault(barcode, 0) + 1);
  7.         }
  8.         PriorityQueue<int[]> queue = new PriorityQueue<>((a, b) -> b[1] - a[1]);
  9.         for (Map.Entry<Integer, Integer> entry : count.entrySet()) {
  10.             int[] unit = {entry.getKey(), entry.getValue()};
  11.             queue.add(unit);
  12.         }
  13.         int start = 0;
  14.         while(queue.size() > 2) {
  15.             int[] front = queue.poll();
  16.             int[] sec = queue.poll();
  17.             ans[start++] = front[0];
  18.             ans[start++] = sec[0];
  19.             if (front[1] > 1) {
  20.                 front[1]--;
  21.                 queue.add(front);
  22.             }
  23.             if (sec[1] > 1) {
  24.                 sec[1]--;
  25.                 queue.add(sec);
  26.             }
  27.         }
  28.         while(queue.size() > 0) {
  29.             int[] front = queue.poll();
  30.             ans[start++] = front[0];
  31.             if (front[1] > 1) {
  32.                 front[1]--;
  33.                 queue.add(front);
  34.             }
  35.         }
  36.         return ans;
  37.     }
  38. }
复制代码
回复

使用道具 举报

🔗
14417335 2019-5-27 02:53:46 | 只看该作者
全局:
欢迎来系统设计题专版讨论系统设计问题: System Design

回复

使用道具 举报

🔗
 楼主| zhangrz2 2019-5-27 04:21:46 | 只看该作者
全局:
284. Peeking Iterator -- you can define your own LinkedList and apply generics to solve this too

  1. // Java Iterator interface reference:
  2. // [url]https://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html[/url]
  3. class PeekingIterator implements Iterator<Integer> {
  4.     boolean hasMore;
  5.     Iterator<Integer> it;
  6.     Integer next;
  7.         public PeekingIterator(Iterator<Integer> iterator) {
  8.             // initialize any member here.
  9.             it = iterator;
  10.         updateNext();
  11.         }

  12.     // Returns the next element in the iteration without advancing the iterator.
  13.         public Integer peek() {
  14.         return this.next;
  15.         }

  16.         // hasNext() and next() should behave the same as in the Iterator interface.
  17.         // Override them if needed.
  18.         @Override
  19.         public Integer next() {
  20.         Integer ans = this.next;
  21.         updateNext();
  22.             return ans;
  23.         }

  24.         @Override
  25.         public boolean hasNext() {
  26.             return hasMore;
  27.         }
  28.    
  29.     private void updateNext() {
  30.         if (it.hasNext()) {
  31.             next = it.next();
  32.             hasMore = true;
  33.         }else {
  34.             hasMore = false;
  35.         }
  36.     }
  37. }
复制代码
回复

使用道具 举报

🔗
 楼主| zhangrz2 2019-5-27 06:40:31 | 只看该作者
全局:
本帖最后由 zhangrz2 于 2019-5-27 06:43 编辑

93. Restore IP Addresses -- family with valid IP format

-- must smaller or equal than 255
-- if the first char is '0', then the length must be 1
more optimal solution--using StringBuilder instead of creating new string at each recursion call

  1. class Solution {
  2.     public List<String> restoreIpAddresses(String s) {
  3.         List<String> ans = new ArrayList<>();
  4.         if (s == null || s.length() == 0) {
  5.             return ans;
  6.         }
  7.         buildList(ans, "", 0, s, 0);
  8.         return ans;
  9.     }
  10.    
  11.     private void buildList(List<String> ans, String str, int curIndex, String s, int count) {
  12.         if (str.length() == s.length() + 4 && count == 4) {
  13.             ans.add(str.substring(1, str.length()));
  14.             return;
  15.         }
  16.         if (count >= 4) {
  17.             return;
  18.         }
  19.         int last = Math.min(curIndex + 3, s.length());
  20.         for (int i = curIndex; i < last; i++) {
  21.             String cur = s.substring(curIndex, i + 1);
  22.             if (isValid(cur)) {
  23.                 buildList(ans, str + "." +  cur, i + 1, s, count + 1);
  24.             }
  25.         }
  26.         return;
  27.     }
  28.    
  29.     private boolean isValid(String str) {
  30.         if (str == null || str.length() == 0) {
  31.             return false;
  32.         }
  33.         int len = str.length();
  34.         if (len > 3) {
  35.             return false;
  36.         }
  37.         if (len != 1 && str.charAt(0) == '0') {
  38.             return false;
  39.         }
  40.         return Integer.parseInt(str) <= 255;
  41.     }
  42. }
复制代码

回复

使用道具 举报

🔗
 楼主| zhangrz2 2019-5-27 08:55:34 | 只看该作者
全局:
本帖最后由 zhangrz2 于 2019-5-27 08:58 编辑

362. Design Hit Counter-- using AtomicIntegerArray to scale(multithreading)

  1. class HitCounter {
  2.     int[] times;
  3.     int[] hits;
  4.     /** Initialize your data structure here. */
  5.     public HitCounter() {
  6.         times = new int[300];
  7.         hits = new int[300];
  8.     }
  9.    
  10.     /** Record a hit.
  11.         @param timestamp - The current timestamp (in seconds granularity). */
  12.     public void hit(int timestamp) {
  13.         int index = timestamp % 300;
  14.         if (times[index] != timestamp) {
  15.             times[index] = timestamp;
  16.             hits[index] = 1;
  17.         }else {
  18.             hits[index]++;
  19.         }
  20.     }
  21.    
  22.     /** Return the number of hits in the past 5 minutes.
  23.         @param timestamp - The current timestamp (in seconds granularity). */
  24.     public int getHits(int timestamp) {
  25.         int ans = 0;
  26.         for (int i = 0; i < times.length; i++) {
  27.             if (times[i] > timestamp - 300) {
  28.                 ans += hits[i];
  29.             }
  30.         }
  31.         return ans;
  32.     }
  33. }

  34. /**
  35. * Your HitCounter object will be instantiated and called as such:
  36. * HitCounter obj = new HitCounter();
  37. * obj.hit(timestamp);
  38. * int param_2 = obj.getHits(timestamp);
  39. */
复制代码
[/i][/i]
回复

使用道具 举报

🔗
 楼主| zhangrz2 2019-5-28 10:20:13 | 只看该作者
全局:
295. Find Median from Data Stream -- so many solutions(any ideas for the follow ups?)

  1. class MedianFinder {
  2.     PriorityQueue<Integer> maxLowHeap;
  3.     PriorityQueue<Integer> minHighHeap;
  4.     /** initialize your data structure here. */
  5.     public MedianFinder() {
  6.         minHighHeap = new PriorityQueue<Integer>();
  7.         maxLowHeap = new PriorityQueue<Integer>((a , b) -> b - a);
  8.     }
  9.    
  10.     public void addNum(int num) {
  11.         maxLowHeap.add(num);
  12.         minHighHeap.add(maxLowHeap.peek());
  13.         maxLowHeap.poll();
  14.         if(maxLowHeap.size() < minHighHeap.size()) {
  15.             maxLowHeap.add(minHighHeap.poll());
  16.         }
  17.     }
  18.    
  19.     public double findMedian() {
  20.         if (maxLowHeap.size() == minHighHeap.size()) {
  21.             return (maxLowHeap.peek() + minHighHeap.peek()) * 0.5;
  22.         }else {
  23.             return maxLowHeap.peek();
  24.         }
  25.     }
  26. }

  27. /**
  28. * Your MedianFinder object will be instantiated and called as such:
  29. * MedianFinder obj = new MedianFinder();
  30. * obj.addNum(num);
  31. * double param_2 = obj.findMedian();
  32. */
复制代码
回复

使用道具 举报

🔗
 楼主| zhangrz2 2019-5-28 10:21:45 | 只看该作者
全局:
zhangrz2 发表于 2019-5-28 10:20
295. Find Median from Data Stream -- so many solutions(any ideas for the follow ups?)

[mw_shl_cod ...

TODO: look up implementing AVL Tree using Java
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 注册账号
隐私提醒:
  • ☑ 禁止发布广告,拉群,贴个人联系方式:找人请去🔗同学同事飞友,拉群请去🔗拉群结伴,广告请去🔗跳蚤市场,和 🔗租房广告|找室友
  • ☑ 论坛内容在发帖 30 分钟内可以编辑,过后则不能删帖。为防止被骚扰甚至人肉,不要公开留微信等联系方式,如有需求请以论坛私信方式发送。
  • ☑ 干货版块可免费使用 🔗超级匿名:面经(美国面经、中国面经、数科面经、PM面经),抖包袱(美国、中国)和录取汇报、定位选校版
  • ☑ 查阅全站 🔗各种匿名方法

本版积分规则

>
快速回复 返回顶部 返回列表