2020年3月17日
- StringBuilder的append方法可以追加任何基本类型
3月18日
- 单链表 包含 数据 和 next指针
- 头节点不包含数据
- 链表插入
- 先定位到要插入的节点的前一个元素
- 修改前节点的next
- 修改插入节点的next
- 定位函数
定位到当前index对应的节点
int i = 0;
cur = head.next;
while (cur != null && i < index) {
cur = cur.next;
i++;
}
3月19日
矩阵操作
1. 按照主对角线交换 a[i][j] -- a[j][i]
for(int i = 0; i < matrix.length; I++){
for (int j = i+1 ; j < matrix.length; j++) {
int tmp = matrix[i][j];
matrix[i][j] = matrix[j][i];
matrix[j][i] = tmp;
}
}
2. 按照副对角线交换 a[i][j] -- a[n-j][n-i]
for (int i = 0; i < matrix.length; i++){
for (int j = 0; j < matrix.length-1-i; j++) {
int tmp = matrix[i][j];
matrix[i][j] = matrix[n-j][n-i];
matrix[n-j][n-i] = tmp;
}
}
3. 按照行上下颠倒
for (int i= 0; i < n/2; i++) {
for( int j = 0; j < matrix.length; j++) {
int tmp = matrix[i][j];
matrix[i][j] = matrix[n-1-i][j];
matrix[n-1-i][j] = tmp;
}
}
4. 顺时针旋转90度 (先上下颠倒, 然后按照主对角线交换)
for (int i =0 ;i < n/2; i++){
for (int j = 0; j < a.length; j++){
int tmp = a[i][j];
a[i][j] = a[n-1-i][j];
a[n-i-1][j] = tmp;
}
}
for (int i = 0; i < a.length; i++){
for (int j = i+1; j < a.length; j++){
int tmp = a[i][j];
a[i][j] = a[j][i];
a[j][i] = tmp;
}
}
5. 逆时针旋转90度(先上下颠倒, 然后按照副对角线交换)
for (int i = 0; i < n/2; i++) {
for (int j = 0; j < n; j++){
int tmp = a[i][j];
a[i][j] = a[n-1-i][j];
a[n-i-1][j] = tmp;
}
}
for (int i = 0; i < n-1; i++){
for (int j = 0; j < n-i-1; j++;){
int tmp = a[i][j];
a[i][j] = a[n-j][n-i];
a[n-j][n-i] = tmp;
}
}
3月20日
查找倒数第K个链表节点
public ListNode FindKthToTail(ListNode head,int k) {
ListNode fast = head, slow = head;
int i = 0;
while (fast != null) {
if (i >= k) {
slow = slow.next;
}
fast = fast.next;
i++;
}
return i < k ? null : slow;
}
链表A+B
public ListNode plusAB(ListNode a, ListNode b) {
// write code here
if (a == null)return b;
if (b == null)return a;
ListNode head = new ListNode(-1);
ListNode cur = head;
int sum = 0;
while (a != null || b != null || sum != 0) {
if (a != null) {
sum += a.val;
a = a.next;
}
if (b != null) {
sum += b.val;
b = b.next;
}
cur.next = new ListNode(sum%10);
cur = cur.next;
sum /= 10;
}
return head.next;
}
用2个栈实现队列
import java.util.Stack;
public class Solution {
Stack<Integer> stack1 = new Stack<Integer>();
Stack<Integer> stack2 = new Stack<Integer>();
public void push(int node) {
stack1.push(node);
}
public int pop() {
if (stack1.empty() && stack2.empty()) {
throw new RuntimeException("Queue is null");
}
if (stack2.empty()) {
while (!stack1.empty()) {
stack2.push(stack1.pop());
}
}
return stack2.pop();
}
}