力扣---2020.7.3

    技术2024-04-03  103

    108. 将有序数组转换为二叉搜索树

    class Solution { public TreeNode sortedArrayToBST(int[] nums) { return nums == null ? null:buildTree(nums,0,nums.length-1); } public TreeNode buildTree(int[] nums,int left,int right){ if(left>right) return null; int mid = left + (right - left)/2; TreeNode root = new TreeNode(nums[mid]); root.left = buildTree(nums,left,mid-1); root.right = buildTree(nums,mid+1,right); return root; } }

    59. 螺旋矩阵 II

    class Solution { public int[][] generateMatrix(int n) { int l = 0, r = n - 1, t = 0, b = n - 1; int[][] mat = new int[n][n]; int num = 1, tar = n * n; while(num <= tar){ for(int i = l; i <= r; i++) mat[t][i] = num++; // left to right. t++; for(int i = t; i <= b; i++) mat[i][r] = num++; // top to bottom. r--; for(int i = r; i >= l; i--) mat[b][i] = num++; // right to left. b--; for(int i = b; i >= t; i--) mat[i][l] = num++; // bottom to top. l++; } return mat; } }

    61. 旋转链表

    /** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ class Solution { public ListNode rotateRight(ListNode head, int k) { if(head==null||k==0){ return head; } ListNode cursor=head; ListNode tail=null;//尾指针 int length=1; while(cursor.next!=null)//循环 得到总长度 { cursor=cursor.next; length++; } int loop=length-(k%length);//得到循环的次数 tail=cursor;//指向尾结点 cursor.next=head;//改成循环链表 cursor=head;//指向头结点 for(int i=0;i<loop;i++){//开始循环 cursor=cursor.next; tail=tail.next; } tail.next=null;//改成单链表 return cursor;//返回当前头 } }

    你知道的越多,你不知道的越多。

    Processed: 0.015, SQL: 9