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. Python基础入门-while循环示例

    闲来无事! 想写一些基础的东西! 比如今天的while循环,,,,,, 很多python初学者,最开始学习python的时候,会被while循环给干蒙蔽! 那么今天,小编为大家讲解一些基础的实例,来帮 ...

  2. 第07章-Spring MVC 的高级技术

    Spring MVC 的高级技术 1. Spring MVC配置的替代方案 1.1 自定义DispatcherServlet配置 AbstractAnnotationConfigDispatcherS ...

  3. Ubuntu安装开发版pidgin支持lwqq插件

    sudo add-apt-repository ppa:lainme/pidgin-lwqq  """添加pidgin-lwqq源""" s ...

  4. ORCHARD学习教程-安装

    安装说明:测试对象为正式版1.8 安装方法: 使用Microsoft Web Platform Installer 利用Microsoft WebMatrix 来安装 Working with Orc ...

  5. SharePoint配置网站集的审核设置

    配置网站集的审核设置 您可以使用 Microsoft SharePoint Server 2010 的审核功能来跟踪哪些用户对网站集的网站.内容类型.列表.库.列表项和库文件执行了哪些操作.了解谁对哪 ...

  6. Eclipse中连接数据库错误:com.microsoft.sqlserver.jdbc.SQLServerException: 之类的错误

    原创 错误:org.apache.jasper.JasperException: Unable to compile class for JSP 原因是页面指令中 import="java. ...

  7. JAVA的IO处理【转】

    I/O简介 IO是输入和输出的简称,在实际的使用时,输入和输出是有方向的.就像现实中两个人之间借钱一样,例如A借钱给B,相对于A来说是借出,而相对于B来说则是借入.所以在程序中提到输入和输出时,也需要 ...

  8. C# 判断一个数是不是奇数/偶数

    一般普通版: private bool IsOdd(int num) { ) == ; } 通过判断取余 现在升级版: private bool IsOdd(int num) { ) == ; } 通 ...

  9. .Net Core 项目部署IIS简单步骤

    1.新建一个解决方案: 我习惯会把运行文件移至一级目录 然后清除CoreTest 文件夹里面的文件 2.在解决方案中新建一个项目 点击确认有,这里有几种选择类型,我一般选择空类型(这里需要注意一下,空 ...

  10. 《C#多线程编程实战》2.10 SpinWait

    emmm 这个SpinWait 中文是自旋等待的意思. 所谓自旋,就是自己追自己影子,周伯通的左右手互博,不好听就是放屁自己追着玩,小狗转圈咬自己的尾巴 SpinWait是一个结构体,并不是一个类. ...