hash & heap - 20181023 - 20181026
129. Rehashing
- /**
- * Definition for ListNode
- * public class ListNode {
- * int val;
- * ListNode next;
- * ListNode(int x) {
- * val = x;
- * next = null;
- * }
- * }
- */
- public class Solution {
- /**
- * @param hashTable: A list of The first node of linked list
- * @return: A list of The first node of linked list which have twice size
- */
- public ListNode[] rehashing(ListNode[] hashTable) {
- // write your code here
- if (hashTable.length == 0) {
- return hashTable;
- }
- int capacity = hashTable.length * 2;
- ListNode[] result = new ListNode[capacity];
- for (ListNode listNode : hashTable) {
- while (listNode != null) {
- int newIndex = (listNode.val % capacity + capacity) % capacity;
- if (result[newIndex] == null) {
- result[newIndex] = new ListNode(listNode.val);
- } else {
- ListNode head = result[newIndex];
- while (head.next != null) {
- head = head.next;
- }
- head.next = new ListNode(listNode.val);
- }
- listNode = listNode.next;
- }
- }
- return result;
- }
- };
134. LRU Cache
- class Node {
- int key;
- int value;
- Node next;
- Node(int key, int value) {
- this.key = key;
- this.value = value;
- this.next = null;
- }
- }
- public class LRUCache {
- int size;
- int capacity;
- Node tail;
- Node dummy;
- Map<Integer, Node> keyToPrevMap;
- /*
- * @param capacity: An integer
- */
- public LRUCache(int capacity) {
- // do intialization if necessary
- this.capacity = capacity;
- this.size = 0;
- this.dummy = new Node(0, 0);
- this.tail = dummy;
- keyToPrevMap = new HashMap<>();
- }
- public void moveRecentNodeToTail(int key) {
- Node prev = keyToPrevMap.get(key);
- Node curr = prev.next;
- if (curr == tail) {
- return;
- }
- prev.next = curr.next;
- tail.next = curr;
- keyToPrevMap.put(key, tail);
- //删掉现节点之后,不仅要改变前指针指向,还需要更新map
- if(prev.next!=null){
- keyToPrevMap.put(prev.next.key,prev);
- }
- tail = curr;
- }
- /*
- * @param key: An integer
- * @return: An integer
- */
- public int get(int key) {
- // write your code here
- if (keyToPrevMap.containsKey(key)) {
- moveRecentNodeToTail(key);
- return tail.value;
- }
- return -1;
- }
- /*
- * @param key: An integer
- * @param value: An integer
- * @return: nothing
- */
- public void set(int key, int value) {
- // write your code here
- if (get(key) != -1) {
- Node prev = keyToPrevMap.get(key);
- prev.next.value = value;
- return;
- }
- //无此值 set并放在队尾
- if (size < capacity) {
- size++;
- Node newNode = new Node(key, value);
- tail.next = newNode;
- keyToPrevMap.put(key, tail);
- tail = newNode;
- return;
- }
- //空间已满,需要删掉头指针: 可以直接替换头指针key-value值,再移到队尾来实现
- Node first = dummy.next;
- keyToPrevMap.remove(first.key);
- first.key = key;
- first.value = value;
- keyToPrevMap.put(key, dummy);
- moveRecentNodeToTail(key);
- }
- }
4. Ugly Number II
method1:用优先队列
- public class Solution {
- /**
- * @param n: An integer
- * @return: the nth prime number as description.
- */
- public int nthUglyNumber(int n) {
- // write your code here
- Queue<Long> queue = new PriorityQueue<>();
- Set<Long> set = new HashSet<>();
- int[] factors = new int[3];
- factors[0] = 2;
- factors[1] = 3;
- factors[2] = 5;
- queue.add(1L);
- Long number = 0L;
- for (int i = 0; i < n; i++) {
- number = queue.poll();
- for (int j = 0; j < 3; j++) {
- if (!set.contains(number * factors[j])) {
- queue.add(number * factors[j]);
- set.add(number * factors[j]);
- }
- }
- }
- return number.intValue();
- }
- }
method2: 丑数一定是某一个丑数*2或者*3或者*5的结果,维护三个指针,例如如果该指针*2结果大于上一个丑数,指针+1
- public class Solution {
- /**
- * @param n: An integer
- * @return: the nth prime number as description.
- */
- public int nthUglyNumber(int n) {
- // write your code here
- List<Integer> res = new ArrayList<>();
- res.add(1);
- int p2 = 0;
- int p3 = 0;
- int p5 = 0;
- for (int i = 1; i < n; i++) {
- int lastNum = res.get(res.size() - 1);
- while (res.get(p2) * 2 <= lastNum) p2++;
- while (res.get(p3) * 3 <= lastNum) p3++;
- while (res.get(p5) * 5 <= lastNum) p5++;
- res.add(Math.min(Math.min(res.get(p2) * 2, res.get(p3) * 3), res.get(p5) * 5));
- }
- return res.get(n - 1);
- }
- }
545. Top k Largest Numbers II
- public class Solution {
- private int maxSize;
- private Queue<Integer> minHeap;
- /*
- * @param k: An integer
- */
- public Solution(int k) {
- // do intialization if necessary
- this.maxSize = k;
- this.minHeap = new PriorityQueue<>();
- }
- /*
- * @param num: Number to be added
- * @return: nothing
- */
- public void add(int num) {
- // write your code here
- if (minHeap.size() < maxSize) {
- minHeap.offer(num);
- return;
- }
- if (num > minHeap.peek()) {
- minHeap.poll();
- minHeap.offer(num);
- }
- }
- /*
- * @return: Top k element
- */
- public List<Integer> topk() {
- // write your code here
- List<Integer> res = new ArrayList<>();
- for (Integer num : minHeap) {
- res.add(num);
- }
- Collections.sort(res);
- Collections.reverse(res);
- return res;
- }
- }
104. Merge K Sorted Lists
method1:利用最小堆
- /**
- * Definition for ListNode.
- * public class ListNode {
- * int val;
- * ListNode next;
- * ListNode(int val) {
- * this.val = val;
- * this.next = null;
- * }
- * }
- */
- public class Solution {
- private Comparator<ListNode> listNodeComparator = new Comparator<ListNode>() {
- @Override
- public int compare(ListNode o1, ListNode o2) {
- return (o1.val - o2.val);
- }
- };
- /**
- * @param lists: a list of ListNode
- * @return: The head of one sorted list.
- */
- public ListNode mergeKLists(List<ListNode> lists) {
- // write your code here
- if (lists == null || lists.size() == 0) {
- return null;
- }
- Queue<ListNode> minheap = new PriorityQueue<>(lists.size(), listNodeComparator);
- for (ListNode node : lists) {
- if(node != null){
- minheap.add(node);
- }
- }
- ListNode dummy = new ListNode(0);
- ListNode tail = dummy;
- while (!minheap.isEmpty()) {
- ListNode head = minheap.poll();
- tail.next = head;
- tail = head;
- if (head.next != null) {
- minheap.add(head.next);
- }
- }
- return dummy.next;
- }
- }
method2: merge 2 by 2(待二刷)
method3: 分治(待二刷)
613. High Five
- /**
- * Definition for a Record
- * class Record {
- * public int id, score;
- * public Record(int id, int score){
- * this.id = id;
- * this.score = score;
- * }
- * }
- */
- public class Solution {
- /**
- * @param results a list of <student_id, score>
- * @return find the average of 5 highest scores for each person
- * Map<Integer, Double> (student_id, average_score)
- */
- public Map<Integer, Double> highFive(Record[] results) {
- // Write your code here
- Map<Integer, Double> resMap = new HashMap<>();
- if (results == null || results.length == 0) {
- return resMap;
- }
- Map<Integer, PriorityQueue<Integer>> scoreMap = new HashMap<>();
- for (Record record : results) {
- if (!scoreMap.containsKey(record.id)) {
- scoreMap.put(record.id, new PriorityQueue<Integer>());
- }
- PriorityQueue<Integer> heap = scoreMap.get(record.id);
- if (heap.size() < 5) {
- heap.add(record.score);
- continue;
- }
- if (record.score > heap.peek()) {
- heap.poll();
- heap.add(record.score);
- }
- }
- for (Map.Entry<Integer, PriorityQueue<Integer>> entry : scoreMap.entrySet()) {
- PriorityQueue<Integer> scoreHeap = entry.getValue();
- int sum = 0;
- while (!scoreHeap.isEmpty()) {
- sum += scoreHeap.poll();
- }
- double ave = sum / 5.0;
- resMap.put(entry.getKey(), ave);
- }
- return resMap;
- }
- }
612. K Closest Points
- public class Solution {
- /**
- * @param points: a list of points
- * @param origin: a point
- * @param k: An integer
- * @return: the k closest points
- */
- public Point[] kClosest(Point[] points, Point origin, int k) {
- // write your code here
- if (points == null || points.length < k || k == 0) {
- return null;
- }
- Comparator<Point> comparator = new Comparator<Point>() {
- @Override
- public int compare(Point o1, Point o2) {
- return compareDistance(o2, o1, origin);
- }
- };
- Point[] res = new Point[k];
- PriorityQueue<Point> maxHeap = new PriorityQueue<>(comparator);
- for (Point point : points) {
- if (maxHeap.size() < k) {
- maxHeap.add(point);
- continue;
- }
- if (compareDistance(point, maxHeap.peek(), origin) < 0) {
- maxHeap.poll();
- maxHeap.add(point);
- }
- }
- for (int i = k - 1; i >= 0; i--) {
- res[i] = maxHeap.poll();
- }
- return res;
- }
- private int compareDistance(Point o1, Point o2, Point center) {
- int distance1 = (o1.x - center.x) * (o1.x - center.x) + (o1.y - center.y) * (o1.y - center.y);
- int distance2 = (o2.x - center.x) * (o2.x - center.x) + (o2.y - center.y) * (o2.y - center.y);
- if (distance1 == distance2) {
- return o1.x != o2.x ? o1.x - o2.x : o1.y - o2.y;
- }
- return distance1 - distance2;
- }
- }
81. Find Median from Data Stream
- public class Solution {
- /**
- * @param nums: A list of integers
- * @return: the median of numbers
- */
- //此题中位数定义和一般的有区别,写的时候需要注意
- //存储后半部分的数据
- private PriorityQueue<Integer> minHeap;
- //存储前半部分的数据
- private PriorityQueue<Integer> maxHeap;
- private int count;//已加入的数
- public int[] medianII(int[] nums) {
- // write your code here
- if (nums == null || nums.length == 0) {
- return null;
- }
- int len = nums.length;
- int[] res = new int[len];
- Comparator<Integer> maxComparator = new Comparator<Integer>() {
- @Override
- public int compare(Integer o1, Integer o2) {
- return o2.compareTo(o1);
- }
- };
- minHeap = new PriorityQueue<>(len);
- maxHeap = new PriorityQueue<>(len, maxComparator);
- for (int i = 0; i < len; i++) {
- addNumber(nums[i]);
- res[i] = getMedian();
- }
- return res;
- }
- public void addNumber(int num) {
- maxHeap.add(num);
- count++;
- //总是先add前半部分数,保证maxHeap.size()>=minHeap.size()
- if (count % 2 == 1) {
- if (minHeap.isEmpty()) {
- return;
- }
- //交换堆顶,保证有序
- if (maxHeap.peek() > minHeap.peek()) {
- int maxPeek = maxHeap.poll();
- int minPeek = minHeap.poll();
- minHeap.add(maxPeek);
- maxHeap.add(minPeek);
- }
- return;
- }
- //当count为奇数时,maxHeap.size-minHeap.size=1,因而当count变为偶数时,只用无脑再将peek取出添到后半部分
- minHeap.add(maxHeap.poll());
- return;
- }
- public int getMedian() {
- return maxHeap.peek();
- }
- }
401. Kth Smallest Number in Sorted Matrix
此题注意应该维护的是最小堆,很容易误判成最大堆
- class Pair {
- private int x;
- private int y;
- private int val;
- public Pair(int x, int y, int val) {
- this.x = x;
- this.y = y;
- this.val = val;
- }
- public int getX() {
- return x;
- }
- public void setX(int x) {
- this.x = x;
- }
- public int getY() {
- return y;
- }
- public void setY(int y) {
- this.y = y;
- }
- public int getVal() {
- return val;
- }
- public void setVal(int val) {
- this.val = val;
- }
- }
- public class Solution {
- /**
- * @param matrix: a matrix of integers
- * @param k: An integer
- * @return: the kth smallest number in the matrix
- */
- public int kthSmallest(int[][] matrix, int k) {
- // write your code here
- if (matrix == null || matrix.length == 0 || matrix.length * matrix[0].length < k) {
- return -1;
- }
- Comparator<Pair> comparator = new Comparator<Pair>() {
- @Override
- public int compare(Pair o1, Pair o2) {
- return o1.getVal() - o2.getVal();
- }
- };
- int r = matrix.length;
- int c = matrix[0].length;
- PriorityQueue<Pair> minHeap = new PriorityQueue<>(comparator);
- boolean[][] visited = new boolean[r][c];
- minHeap.add(new Pair(0, 0, matrix[0][0]));
- visited[0][0] = true;
- for (int i = 1; i <= k - 1; i++) {
- Pair cur = minHeap.poll();
- if (cur.getX() + 1 < r && !visited[cur.getX() + 1][cur.getY()]) {
- minHeap.add(new Pair(cur.getX() + 1, cur.getY(), matrix[cur.getX() + 1][cur.getY()]));
- visited[cur.getX() + 1][cur.getY()] = true;
- }
- if (cur.getY() + 1 < c && !visited[cur.getX()][cur.getY() + 1]) {
- minHeap.add(new Pair(cur.getX(), cur.getY() + 1, matrix[cur.getX()][cur.getY() + 1]));
- visited[cur.getX()][cur.getY() + 1] = true;
- }
- }
- return minHeap.peek().getVal();
- }
- }
hash & heap - 20181023 - 20181026的更多相关文章
- 用oracle建表,必须注意Oracle 关键字(保留字)
Oracle 关键字(保留字) 大全 转 其实这个东西可以在oracle 上输入一个sql语句就可以得到: select * from v$reserved_words order by keyw ...
- 几种常见 容器 比较和分析 hashmap, map, vector, list ...hash table
list支持快速的插入和删除,但是查找费时; vector支持快速的查找,但是插入费时. map查找的时间复杂度是对数的,这几乎是最快的,hash也是对数的. 如果我自己写,我也会用二叉检索树,它在 ...
- 关于Hash集合以及Java中的内存泄漏
<学习笔记>关于Hash集合以及Java中的内存泄漏 标签: 学习笔记内存泄露hash 2015-10-11 21:26 58人阅读 评论(0) 收藏 举报 分类: 学习笔记(5) 版 ...
- sort 树 hash 排序
STL 中 sort 函数用法简介 做 ACM 题的时候,排序是一种经常要用到的操作.如果每次都自己写个冒泡之类的 O(n^2) 排序,不但程序容易超时,而且浪费宝贵的比赛时间,还很有可能写错. ST ...
- Heap and HashHeap
Heap 堆(英语:Heap)是计算机科学中一类特殊的数据结构的统称.堆通常是一个可以被看做一棵树的数组对象.在队列中,调度程序反复提取队列中第一个作业并运行,因为实际情况中某些时间较短的任务将等待很 ...
- OD: Heap Exploit : DWORD Shooting & Opcode Injecting
堆块分配时的任意地址写入攻击原理 堆管理系统的三类操作:分配.释放.合并,归根到底都是对堆块链表的修改.如果能伪造链表结点的指针,那么在链表装卸的过程中就有可能获得读写内存的机会.堆溢出利用的精髓就是 ...
- 海量数据面试题----分而治之/hash映射 + hash统计 + 堆/快速/归并排序
1.从set/map谈到hashtable/hash_map/hash_set 稍后本文第二部分中将多次提到hash_map/hash_set,下面稍稍介绍下这些容器,以作为基础准备.一般来说,STL ...
- Oracle heap 表的主键 dump 分析
1. 创建heap 表: create table t1 (id char(10) primary key,a1 char(10),a2 char(10),a3 char(10)); SQL> ...
- InnoDB关键特性之自适应hash索引
一.索引的资源消耗分析 1.索引三大特点 1.小:只在一个到多个列建立索引 2.有序:可以快速定位终点 3.有棵树:可以定位起点,树高一般小于等于3 2.索引的资源消耗点 1.树的高度,顺序访问索引的 ...
随机推荐
- 云存储上传控件(cloud2)-Xproer.CloudUploader
版权所有 2009-2016荆门泽优软件有限公司 保留所有权利 官方网站:http://www.ncmem.com/ 产品首页:http://www.ncmem.com/webapp/up6.2/in ...
- (转)C# HTML解析示例---星星引发的血案
原文地址:http://www.cnblogs.com/wurang/archive/2013/06/14/3119023.html [前言] 从CSDN转投cnBlog也有一段时间了,发现cnBlo ...
- 20169219 实验二 Java面向对象程序设计
实验二 Java面向对象程序设计 一.程序设计中临时变量的使用 任务: //定义一个数组 int arr[] = {1,2,3,4,5,6,7,8}; //打印原始数组的值 for(int i:arr ...
- Linux:SSH免密码登录
1.使用包管理器安装openssh: 本人的系统是Arch Linux,因此安装命令为:sudo pacman -S openssh 2.使用ssh-keygen命令创建公钥: #ssh-keygen ...
- POJ1753 Flip Game(位运算+暴力枚举)
Flip game is played on a rectangular 4x4 field with two-sided pieces placed on each of its 16 square ...
- Android下拉选择框之PopupWindow
1.效果图 2.思路分析 1.点击弹出对话框 popupwindow 2.对popupwindow进行相关设置,popupwindow中设置view为listview 3.listview中item设 ...
- windows phone 换肤(2)
//这里有篇参考文章 http://www.cnblogs.com/tianhonghui/p/3373276.html#commentform 以下思路是来自徐老师,昨晚看了一个晚上球赛,睡了不到6 ...
- { "result": null, "log_id": 304592860300941982, "error_msg": "image check fail", "cached": 0, "error_code": 222203, "timestamp": 1556030094 }
这个是人脸识别时无法检测到图片报的错,有时候我们检测一张图片是否在库里面,当一张图片明显在里面,还检测不到,如下面是我的代码 package Test1; import java.io.IOExcep ...
- Google的C++代码规范
英文版:http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml 中文版:http://zh-google-styleguide ...
- Redhat7无法启动mysql
是这样的,7的这个环境安装了叫MariaDB了 安装MariaDB之后必须先启动MariaDB [root@redhatx ~]# yum -y install mysql [root@redhatx ...