7月算法训练------第二十一天(堆(优先队列))解题报告
题目类型:堆(优先队列)
题目难度:中等
第一题、2336. 无限集中的最小数字
- 题目链接:2336. 无限集中的最小数字
- 思路分析:
要用一个哈希表来存储元素,以防止元素重复,再用java中的优先队列对本体进行操作。
之前一直在想,用LinkedList或者ArrayList当作哈希表一步到位的操作,但有些测试用例总是超出时间复杂度。 - 代码:
class SmallestInfiniteSet {
Set<Integer> set = new HashSet();
PriorityQueue<Integer> pq = new PriorityQueue<Integer>();
int n = 1; // n为非离散区间的起始位置
public SmallestInfiniteSet() {
}
public int popSmallest() {
if (set.isEmpty()) return n++;
int res = pq.poll();
set.remove(res);
return res;
}
public void addBack(int num) {
if (num < n && set.add(num)) pq.add(num);
}
}
剑指offer自行加练题目
第二题、剑指 Offer 03. 数组中重复的数字
- 题目链接:剑指 Offer 03. 数组中重复的数字
- 思路分析:
很明显,用哈希表就能完美解决。 - 代码:
class Solution {
public int findRepeatNumber(int[] nums) {
Set<Integer> set = new HashSet();
for(int i = 0; i < nums.length; i++){
if(set.contains(nums[i])){
return nums[i];
}else{
set.add(nums[i]);
}
}
return 0;
}
}
第三题、剑指 Offer 06. 从尾到头打印链表
- 题目链接:剑指 Offer 06. 从尾到头打印链表
- 思路分析:
遍历链表元素,然后将值用栈存储起来,根据栈先进后出的特点,就能将链表反转打印。 - 代码:
class Solution {
public int[] reversePrint(ListNode head) {
Stack<Integer> st = new Stack();
while(head!=null){
st.push(head.val);
head = head.next;
}
int[] res = new int[st.size()];
for(int i = 0; i < res.length; i++){
res[i] = st.pop();
}
return res;
}
}
第四题、剑指 Offer 24. 反转链表
- 题目链接:剑指 Offer 24. 反转链表
- 思路分析:
指定一个当前节点的前一个结点,当前节点的后一个节点,将当前节点的下一个指向前一个节点,将前节点更新为当前节点,然后更新当前节点的值为下一个节点。注意:这里不能将顺序调换。 - 代码:
class Solution {
public ListNode reverseList(ListNode head) {
ListNode pre = null, cur;
cur = head;
while(cur != null){
ListNode after = cur.next; // 自己写错的地方,写成了haed.next;
cur.next = pre;
pre = cur;
cur = after;
}
return pre;
}
}
第五题、剑指 Offer 35. 复杂链表的复制
- 题目链接:剑指 Offer 35. 复杂链表的复制
- 思路分析:
刚开始想的时候,感觉和普通的链表复制差不多,然后写了一会才发现,这个链表随机指向是真的不好解决,这也是本题的难点。采用一个map集合将,采用递归调用,创建它的下一个节点和随机节点。 - 代码:
class Solution {
Map<Node, Node> cachedNode = new HashMap<Node, Node>();
public Node copyRandomList(Node head) {
if (head == null) {
return null;
}
if (!cachedNode.containsKey(head)) {
Node headNew = new Node(head.val);
cachedNode.put(head, headNew);
headNew.next = copyRandomList(head.next);
headNew.random = copyRandomList(head.random);
}
return cachedNode.get(head);
}
}