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的更多相关文章

  1. 用oracle建表,必须注意Oracle 关键字(保留字)

    Oracle 关键字(保留字) 大全   转 其实这个东西可以在oracle 上输入一个sql语句就可以得到: select * from v$reserved_words order by keyw ...

  2. 几种常见 容器 比较和分析 hashmap, map, vector, list ...hash table

    list支持快速的插入和删除,但是查找费时; vector支持快速的查找,但是插入费时. map查找的时间复杂度是对数的,这几乎是最快的,hash也是对数的.  如果我自己写,我也会用二叉检索树,它在 ...

  3. 关于Hash集合以及Java中的内存泄漏

    <学习笔记>关于Hash集合以及Java中的内存泄漏 标签: 学习笔记内存泄露hash 2015-10-11 21:26 58人阅读 评论(0) 收藏 举报  分类: 学习笔记(5)  版 ...

  4. sort 树 hash 排序

    STL 中 sort 函数用法简介 做 ACM 题的时候,排序是一种经常要用到的操作.如果每次都自己写个冒泡之类的 O(n^2) 排序,不但程序容易超时,而且浪费宝贵的比赛时间,还很有可能写错. ST ...

  5. Heap and HashHeap

    Heap 堆(英语:Heap)是计算机科学中一类特殊的数据结构的统称.堆通常是一个可以被看做一棵树的数组对象.在队列中,调度程序反复提取队列中第一个作业并运行,因为实际情况中某些时间较短的任务将等待很 ...

  6. OD: Heap Exploit : DWORD Shooting & Opcode Injecting

    堆块分配时的任意地址写入攻击原理 堆管理系统的三类操作:分配.释放.合并,归根到底都是对堆块链表的修改.如果能伪造链表结点的指针,那么在链表装卸的过程中就有可能获得读写内存的机会.堆溢出利用的精髓就是 ...

  7. 海量数据面试题----分而治之/hash映射 + hash统计 + 堆/快速/归并排序

    1.从set/map谈到hashtable/hash_map/hash_set 稍后本文第二部分中将多次提到hash_map/hash_set,下面稍稍介绍下这些容器,以作为基础准备.一般来说,STL ...

  8. Oracle heap 表的主键 dump 分析

    1. 创建heap 表: create table t1 (id char(10) primary key,a1 char(10),a2 char(10),a3 char(10)); SQL> ...

  9. InnoDB关键特性之自适应hash索引

    一.索引的资源消耗分析 1.索引三大特点 1.小:只在一个到多个列建立索引 2.有序:可以快速定位终点 3.有棵树:可以定位起点,树高一般小于等于3 2.索引的资源消耗点 1.树的高度,顺序访问索引的 ...

随机推荐

  1. Java日志组件logback使用:加载非类路径下的配置文件并设置定时更新

    Java日志组件logback使用:加载非类路径下的配置文件并设置定时更新 摘自: https://blog.csdn.net/johnson_moon/article/details/7887449 ...

  2. SQL Server 时间类型转换函数

    cast ( expression as data_type(length))convert ( data_type (length), expression, style) //如果未指定 leng ...

  3. C# winform中Setting.settings 相关知识点

    1.在Settings.settings文件中定义配置字段.包含字段名.类型.范围.值四部分的属性. 字段名.类型和值类似编程中字段的定义一样使用,不再过多的解释.重点讲一下”范围“字段的含义与区别. ...

  4. mysql 全文搜索 FULLTEXT

    到 3.23.23 时,MySQL 开始支持全文索引和搜索.全文索引在 MySQL 中是一个 FULLTEXT 类型索引.FULLTEXT 索引用于 MyISAM 表,可以在 CREATE TABLE ...

  5. Android sutdio单元测试 简单使用步骤

    1.简介 单元测试(unit testing),是指对软件中的最小可测试单元进行检查和验证.比如一个函数,一个方法等 2.添加依赖 dependencies { testCompile 'junit: ...

  6. C#调用OCX控件的常用方法[转]

    小伙伴们在使用ICP提供的各种能力进行集成开发时常常会遇到一些技术上的困扰,例如ICP中很多接口是通过OCX控件的方式提供的,如何调用这些接口,就成了一个不大不小的问题,毕竟开发指南上可没这些内容啊~ ...

  7. dubbo服务治理中间件,zookeeper注册中心 安装配置

    对传统项目架构进行拆分: 集群概念: 面向服务分布式架构: 服务层提供被注册的对象需要实现序列化接口Serializable: 配置表现层和服务层: 依赖包: 服务层: <!-- 定义dubbo ...

  8. python 安装虚拟环境步骤

    1.python3.6.3 注: 1.安装的时候,装上你的pip 2.安装的时候,把环境变量记得勾选 3.如果你手动更改安装位置,更改到随意的盘根目录下 2.MySQL      pycharm最好安 ...

  9. 洛谷P4011 孤岛营救问题(状压+BFS)

    传送门 和网络流有半毛钱关系么…… 可以发现$n,m,p$都特别小,那么考虑状压,每一个状态表示位置以及钥匙的拥有情况,然后每次因为只能走一步,所以可以用bfs求出最优解 然后是某大佬说的注意点:每个 ...

  10. 图层锁定vlisp函数高版本图元自动淡色显示

    (defun c:tt(/ obj) (sk_layerLock (getvar "clayer") nil) (princ) ) ;;;name:sk_layerLock ;;; ...