Leetcode 相关知识点 day4
/用于作者每日有需所作笔记/
1.链表
新建链表进行操作时,常用
ListNode dummyHead = new ListNode(-1);
ListNode temp = dummyHead;
后续对temp操作
链表最常用的方法,拆开归并排序!!!
链表排序一般采用回溯把它全部拆开,在归并。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode sortList(ListNode head) {
if(head == null || head.next == null){
return head;
}
ListNode slow = head;
ListNode fast = head.next;
while(fast != null && fast.next != null){
slow = slow.next;
fast = fast.next.next;
}
ListNode mid = slow.next;
slow.next = null;
return merge(sortList(head),sortList(mid));
}
public ListNode merge(ListNode head,ListNode mid) {
ListNode dummyHead = new ListNode(-1);
ListNode temp = dummyHead;
while(head != null && mid != null){
if(head.val < mid.val){
temp.next = head;
head = head.next;
}else{
temp.next = mid;
mid = mid.next;
}
temp = temp.next;
}
while(head != null){
temp.next = head;
head = head.next;
temp = temp.next;
}
while(mid != null){
temp.next = mid;
mid = mid.next;
temp = temp.next;
}
return dummyHead.next;
}
}
2.相交链表
使用双指针的方法,可以将空间复杂度降至 O(1)O(1)。
每步操作需要同时更新指针 pA 和 pB。
如果指针 pA 不为空,则将指针 pA 移到下一个节点;如果指针 pB 不为空,则将指针 pB 移到下一个节点。
如果指针 pA 为空,则将指针 pA 移到链表headB 的头节点;如果指针 pB 为空,则将指针 pB 移到链表 headA 的头节点。
当指针pA 和pB 指向同一个节点或者都为空时,返回它们指向的节点或者 null。
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
if (headA == null || headB == null) {
return null;
}
ListNode pA = headA, pB = headB;
while (pA != pB) {
pA = pA == null ? headB : pA.next;
pB = pB == null ? headA : pB.next;
}
return pA;
}
}
3.二叉搜索树的中序遍历
public int kthSmallest(TreeNode root, int k) {
List res = new ArrayList<Integer>();
Stack<TreeNode> stack = new Stack();
TreeNode node = root;
while(true){
if(node==null && stack.size()==0){
break;
}
while(node != null){
stack.push(node);
node = node.left;
}
node = stack.pop();//左节点为空就弹出,并将指针调到最后一个左节点
res.add(node.val);
if(res.size() == k){
break;
}
node = node.right;//左节点遍历完就从右节点出发遍历,若没有右节点,
// 则下次循环会继续pop,并将指针调到再上一级。
}
return res;
}
4.数组自定义排序
Integer a[]=new Integer[]{34,4,45,12,92,9};
Arrays.sort(a, new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o2-o1;
}
});
5.List
删除指定元素;
List<Integer> temp = new ArrayList<>();
temp.remove(Integer.valueOf(值));
public static int sumEven(List<Integer> li) {
int sum = 0;
for (Integer i: li)
if (i % 2 == 0)
sum += i;
return sum;
}
// 编译器把上面的代码转化成了下面的样子
public static int sumEven(List<Integer> li) {
int sum = 0;
for (Integer i : li)
if (i.intValue() % 2 == 0)
sum += i.intValue();
return sum;
}