7月算法训练------第十二天(链表)解题报告
题目类型:链表
题目难度:简单
第一题、707. 设计链表
- 题目链接:707. 设计链表
- 思路分析:
最基本的链表的增删查,但要注意循环和if
语句的边界条件。 - 代码:
class MyLinkedList {
MyList head;
int size;
public MyLinkedList() {
head = new MyList(0);
size = 0;
}
public int get(int index) {
if (index < 0 || index >= size) return -1;
MyList temp = head;
for(int i = 0; i <= index; i++){
temp = temp.next;
}
return temp.val;
}
public void addAtHead(int val) {
MyList m = new MyList(val);
size++;
m.next = head.next;
head.next = m;
}
public void addAtTail(int val) {
addAtIndex(size, val);
}
public void addAtIndex(int index, int val) {
if(index > size) return;
if(index < 0) index = 0;
size++;
MyList temp = head;
for(int i = 0; i < index; i++){
temp = temp.next;
}
MyList my = new MyList(val);
my.next = temp.next;
temp.next = my;
}
public void deleteAtIndex(int index) {
if(index < 0 || index >= size){
return;
}
size--;
MyList my = head;
for(int i = 0; i < index; i++){
my = my.next;
}
my.next = my.next.next;
}
}
class MyList{
int val;
MyList next;
public MyList(){
}
public MyList(int val, MyList next){
this.val = val;
this.next = next;
}
public MyList(int val){
this.val = val;
}
}
/**
* Your MyLinkedList object will be instantiated and called as such:
* MyLinkedList obj = new MyLinkedList();
* int param_1 = obj.get(index);
* obj.addAtHead(val);
* obj.addAtTail(val);
* obj.addAtIndex(index,val);
* obj.deleteAtIndex(index);
*/
第二题、2326. 螺旋矩阵 IV
- 题目链接:2326. 螺旋矩阵 IV
- 思路分析:
- 定义四个方向,按照右下左上顺时针方向进行排列;
- 因为题目中
0 <= Node.val <= 1000
,所以我们可以为矩阵初始化为所有元素均为-1
,在后面赋值过程中,如果元素不为-1
,则表示该元素已被访问过,不能再访问。 - 模拟从0 0点开始,方向为0,每次走一步,如果发现走到的点已走过,或者超出边界,则方向+1(注意方向为3时,加1后变成0);
- 一直走直到整个链表遍历完毕。
- 代码:
/**
* 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 {
int[][] dir = {
{0,1},
{1,0},
{0,-1},
{-1,0}
};
public int[][] spiralMatrix(int m, int n, ListNode head) {
int[][] matrix = new int[m][n];
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
matrix[i][j] = -1;
}
}
int r = 0, c = 0, d = 0;
while(head != null){
int val = head.val;
matrix[r][c] = val;
r += dir[d][0];
c += dir[d][1];
int dcnt = 0;
while(r < 0 || r >= m || c < 0 || c >= n || matrix[r][c] != -1){
r -= dir[d][0];
c -= dir[d][1];
d = (d + 1) % 4;
r += dir[d][0];
c += dir[d][1];
if(++dcnt > 4){
break;
}
}
head = head.next;
}
return matrix;
}
}