LC59. 螺旋矩阵 II
//定义四条边left,right,top,bottom通过一个计数器控制循环次数,并且根据四条边来填充数字
class Solution {
public int[][] generateMatrix(int n) {
int l = 0,t = 0,b = n - 1,r = n - 1;
int[][] arr = new int[n][n];
int num = 1;
int target = n * n;
while(num <= target){
for(int i = l;i <= r;i++) arr[t][i] = num++;
t++;
for(int i = t;i <= b;i++) arr[i][r] = num++;
r--;
for(int i = r;i >= l;i--) arr[b][i] = num++;
b--;
for(int i = b;i >= t;i--) arr[i][l] = num++;
l++;
}
return arr;
}
}
LC7整数反转
class Solution {
public int reverse(int x) {
//因为res定死已经是int,10位数反转最后一位一定是1或2不用看了
int res = 0;
while(x != 0){
int temp = x % 10;
//和反转过后的前九位数字进行一个比较操作
if(res > Integer.MAX_VALUE / 10 || res < Integer.MIN_VALUE / 10)
return 0;
res = res * 10 + temp;
x = x / 10;
}
return res;
}
}
LC61旋转链表
//确定好链表长度,并且求出转移点的前一个位置。这里的求法有操作,k = length - k % length,超出的部分根据余数来进行确定位置,即使不够长度那么也可以直接定位到原链表末尾,因为length开始定义为1,那么确定转移点的位置先自减。最终将成环链表切断返回head即可。
/**
* 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 rotateRight(ListNode head, int k) {
if(head == null)
return head;
int length = 1;
//定义一个pre指针去指向转移前的一个点的位置
ListNode pre = head;
//先确定好链表的长度
while(pre.next != null){
pre = pre.next;
length++;
}
//链表成环
pre.next = head;
//将指针进行一个转移操作
k = length - k % length;
pre = head;
while(--k > 0){
pre = pre.next;
}
//将转移点位置确定好以后改变头节点位置
head = pre.next;
//并且将链表切断
pre.next = null;
return head;
}
}