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.树的高度,顺序访问索引的 ...
随机推荐
- SP1557 GSS2 - Can you answer these queries II
一开始看不懂题解,看懂了题解之后觉得还是挺妙的. 好多题解里都提到了HH的项链,但是我觉得关系并不大啊…… 先把所有询问离线下来按照右端点排序,按照询问的要求一个一个加入数字,怎么加入数字,我们设计一 ...
- javascript总结4:javascript常见变量
1 javascript变量 定义:变量在计算机中,是用于存储信息的"容器". 2 使用方法: 2-1 定义变量: var n1; 2-2 变量赋值: var n2=23.45; ...
- ApplicationContex是干啥的
ApplicationContext就是一个百宝箱 ApplicationContext是Spring的核心,Context我们通常解释为上下文环境,我想用“容器”来表述它更容易理解一些,Applic ...
- web.xml配置及详解
1.web.xml 是网络程序中的一个很重要的配置文件. 2.XML基础标准是为XML的进一步实用化制定的标准,它规定了采用XML制定标准时的一些公用特征.方法或规则.XML Schema描述了更加严 ...
- PHP foreach引用&
将以下代码打印 $variable = ['a', 'b', 'c']; foreach ($variable as $key => &$value) { } foreach ($var ...
- [.net 多线程]Monitor
Monitor 类通过向单个线程授予对象锁来控制对对象的访问.对象锁提供限制访问代码块(通常称为临界区)的能力.当一个线程拥有对象的锁时,其他任何线程都不能获取该锁.还可以使用 Monitor 来确保 ...
- 以太坊系列之十八: 百行go代码构建p2p聊天室
百行go代码构建p2p聊天室 百行go代码构建p2p聊天室 1. 上手使用 2. whisper 原理 3. 源码解读 3.1 参数说明 3.1 连接主节点 3.2 我的标识 3.2 配置我的节点 3 ...
- go的Type switch是一个switch语句么?
相信这样的语句在go中大家见的很多 switch t := arg.(type) { default: fmt.Printf("unexpected type %T\n", t) ...
- sqlServer基础知识
sqlServer 基础知识 大纲 创建数据库 1 创建表 2 备份表 3 删除表 4 修改表 5 查询出重复的数据 6 增删改查 7 添加约束 8 分页存储过程 9 排序 10 类型转换 11 ...
- dubbo 面试题
dubbo是什么 dubbo是一个分布式框架,远程服务调用的分布式框架,其核心部分包含:集群容错:提供基于接口方法的透明远程过程调用,包括多协议支持,以及软负载均衡,失败容错,地址路由,动态配置等 ...