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.树的高度,顺序访问索引的 ...
随机推荐
- setnx()
setnx(key,value):当指定的key不存在时,为你设置指定的值
- Entity Framework edmx(mapping文件)
<?xml version="1.0" encoding="utf-8"?><edmx:Edmx Version="2.0" ...
- Laravel 测试教程
参考链接:https://laravel-news.com/seeding-data-testing 迁移文件 修改 database/migrations/2014_10_12_000000_cre ...
- orcad找不到dll
如果运行Capture.exe找不到cdn_sfl401as.dll,如果运行allegro.exe找不到cnlib.dll,(上面俩个库文件都在C:/Cadence/SPB_16.3/tools/b ...
- Redesign Your App for iOS 7 之 页面布局【转】
前言 iOS7是目前iOS史上最颠覆的一次改版. 它的出现令人兴奋,因为它将会带我们进入一个全新的时代: 它的到来也让我们忧心,因为它颠覆了一切,包括我们过去做过的很多努力. 但是,相信大家乐意为这个 ...
- C#存取数据库图片
form1 using System; using System.Collections.Generic; using System.ComponentModel; using System.Data ...
- 21天学通C++学习笔记(三):变量和常量
1. 简述 内存是一种临时存储器,也被称为随机存取存储器(RAM),所有的计算机.智能手机及其他可编程设备都包含微处理器和一定数量的内存,用地址来定位不同的存储区域,像编号一样. 硬盘可以永久的存储数 ...
- this指针------新标准c++程序设计
背景: c++是在c语言的基础上发展而来的,第一个c++的编译器实际上是将c++程序翻译成c语言程序,然后再用c语言编译器进行编译.c语言没有类的概念,只有结构,函数都是全局函数,没有成员函数.翻 ...
- WPF中XAML的触发器的属性,事件 都有那些?以及如何寻找
在编写XAML的触发器时,会有属性,事件. 那么这些都是哪里来的呢? 属性,是附加属性或者依赖属性 事件,那就是事件. 如何寻找呢? 很简单,在想要使用的触发器的对象上(也就是有光标的时候)按下F12 ...
- React基础篇 (1)-- render&components
render 基础用法 //1.创建虚拟DOM元素对象 var vDom=<h1>hello wold!</h1> //2.渲染 ReactDOM.render(vDom,do ...