LeetCode热题100道-day03
1. 括号生成
22. 括号生成
- 剩余左括号总数要小于等于右括号。递归把所有符合要求的加上去就行了
class Solution {
List<String> res = new ArrayList<>();
public List<String> generateParenthesis(int n) {
if(n <= 0){
return res;
}
getParenthesis("",n,n);
return res;
}
private void getParenthesis(String str,int left, int right) {
if(left == 0 && right == 0 ){
res.add(str);
return;
}
if(left == right){
getParenthesis(str+"(",left-1,right);
}else if(left < right){
if(left > 0){
getParenthesis(str+"(",left-1,right);
}
getParenthesis(str+")",left,right-1);
}
}
}
2. 删除链表的倒数第 N 个结点
19. 删除链表的倒数第 N 个结点
- 使用双指针,先让快指针走n步,然后快慢指针一起动,直到快指针next为null,删除慢指针下一个节点
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode pre = new ListNode(-1);
pre.next = head;
ListNode fast = pre, slow = pre;
while (n != 0) {
fast = fast.next;
n--;
}
while (fast.next != null) {
fast = fast.next;
slow = slow.next;
}
slow.next = slow.next.next;
return pre.next;
}
}
3. 合并两个有序链表
21. 合并两个有序链表
- 定义一个虚拟头节点记录结果,已知两链表有序,比较两链表元素,将较小的节点加入新链表,小的链表后移,每次循环新链表向后移。最后将不是null的节点添加到新链表最后
class Solution {
public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
ListNode pre = new ListNode(-1);
ListNode cur = pre;
while (list1 != null && list2 != null){
if (list1.val <= list2.val){
cur.next = list1;
list1 = list1.next;
}else {
cur.next = list2;
list2 = list2.next;
}
cur = cur.next;
}
cur.next = list1 !=null ?list1:list2;
return pre.next;
}
}
4. 最大频率栈(每日一题)
895. 最大频率栈
- 用一个哈希表存储存入的值和频率,用一个动态数组存储栈,出现一次重复元素,就创建一个栈后入栈;出栈将最后面的栈的栈顶元素弹出;每次添加删除维护哈希表
class FreqStack {
HashMap<Integer, Integer> map;
List<Deque<Integer>> stacks;
public FreqStack() {
map = new HashMap<>();
stacks = new ArrayList<>();
}
public void push(int val) {
Integer time = map.getOrDefault(val, 0);
if (time == stacks.size()){
stacks.add(new ArrayDeque<>());
}
stacks.get(time).push(val);
map.put(val, time+1);
}
public int pop() {
int a = stacks.size() - 1;
Integer pop = stacks.get(a).pop();
if (stacks.get(a).isEmpty()){
stacks.remove(a);
}
map.put(pop, map.get(pop)-1);
return pop;
}
}