学习方法
书:《OutLiers》(异类-不一样的成功启示录)
- Chunk it up(切碎知识点)
- Deliberate practicing(刻意练习)
- Feedback(反馈)
Sorting
Linked List链表
Binary Tree二叉树
Stack 栈(先进后出FILO)数组或链表
Queue队列(先进先出FIFO)
Deque(Double ended queue双端队列)
Hashing
list
spanning tree
Tree
Graph
时间复杂度
空间复杂度
O(N):一个for
O(N^2):2个for
1+2+3+···+n
方法1:
y = 0
for i=1 to n:
y=i+y
方法2:有
y = n*(n+1)/2
递归
斐波那契(Fibonacci arry)
F(n) = F(n-1)+F(n-2)
public int fib(int n){
if(n = 0 | n = 1){
return n;
}
return fib(n-1)+fib(n-2);
}
O(2^N)
Master Theorem(主定律)
查找一维矩阵O(log n),二维是O(N)
排序O(N log N)
数组Array
查找O(1)
insert:O(N)~O(1),平均O(N)
Delete:O(N)~O(1),平均O(N)
链表Linked List
insert:O(1)
Delete:O(1)
单链表:只有next
双链表:有前驱和后继
反转链表(reverse Linked List)
public class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}
class Solution {
public ListNode reverseList(ListNode head) {
ListNode cur = head;
ListNode prev = null;
while(cur != null){
ListNode next = cur.next;
cur.next = prev;
prev = cur;
cur = next;
}
return prev;
}
}
二分查找
public int BinarySearch(int[] nums,int target){
int left = 0;
int right = nums.length-1;
int middle;
while(left <= right){
middle = (left + right) / 2;
if(nums[middle] == target){
return middle
}else if(nums[middle] > target){
left = middle+1;
}else if(nums[middle] < target){
right = middle-1;
}
}
return -1;
}
两两交换链表中的节点
public ListNode swapPairs(ListNode head){
if(head == null) return null;
if(head.next == null) return head;
ListNode temp =head.next;
head.next = swapPairs(temp.next);
temp.next = head.next;
return temp.next;
}
或
public ListNode swapPairs(ListNode head) {
ListNode start = new ListNode(0);
start.next = head;
ListNode pre = start;
while(head!=null && head.next!=null){
pre.next = head.next;
head.next = pre.next.next;
pre.next.next = head;
pre = pre.next.next;
head = pre.next;
}
return start.next;
}
环形链表
set判重:O(N)
快指针(走两步)、慢指针(走一步)O(N) 龟兔赛跑
public boolean hasCycle(ListNode head) {
ListNode fast = head;
ListNode slow = head;
while(slow != null && fast != null && fast.next != null){
slow = slow.next;
fast = fast.next.next;
if(slow == fast){
return true;
}
}
return false;
}
括号匹配
利用栈
O(N)
peek( ):查看堆栈顶部的对象
pop( ):移除堆栈顶部的对象
class Solution {
public boolean isValid(String s) {
Stack<Character> stack=new Stack<>();
for (Character c:s.toCharArray()) {
if (c=='(') stack.push(')');
else if (c=='[') stack.push(']');
else if (c=='{') stack.push('}');
else if (stack.isEmpty()||stack.pop()!=c) return false;
}
return stack.isEmpty();
}
}
232用栈实现队列 225
FIFO=>FILO
利用两个栈:输入栈和输入栈