【剑指Offer】注意程序的健壮性
面试题22. 链表中倒数第k个节点
1 /** 2 * Definition for singly-linked list. 3 * public class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode(int x) { val = x; } 7 * } 8 */ 9 class Solution { 10 public ListNode getKthFromEnd(ListNode head, int k) { 11 if(head == null || k == 0){ 12 return null; 13 } 14 ListNode fast = head; 15 ListNode slow = head; 16 while(fast != null && k-- > 0){ 17 fast = fast.next; 18 } 19 if(k > 0){ 20 return null; 21 } 22 while(fast != null && slow != null){ 23 fast = fast.next; 24 slow = slow.next; 25 } 26 return slow; 27 } 28 }
顺时针转圈打印矩阵!(tr,tc) 在左上角 (dr,dc)在右下角 表示这一圈打印的范围 下一圈 即 tr++tc++dr--dc--
打印一圈有三种情况:一种是完整的圈【依次打印顶边、右边、底边、左边】,一种是只有一行(tr==dr,需要从tc打印到dc),一种是只有一列(tc==dc,需要从tr打印到dr)
1 class Solution { 2 private int index; 3 private int[] ans; 4 public int[] spiralOrder(int[][] matrix) { 5 if(matrix == null || matrix.length == 0){ 6 return new int[]{}; 7 } 8 int tr = 0, tc= 0, dr = matrix.length-1, dc = matrix[0].length-1; 9 ans =new int[(dr+1)*(dc+1)]; 10 index = 0; 11 while(tr <= dr && tc <= dc){ 12 process(matrix, tr++, tc++, dr--, dc--); 13 } 14 return ans; 15 } 16 public void process(int[][] matrix, int tr, int tc, int dr, int dc){ 17 if(tr == dr){//只有一行 18 for(int i = tc; i <= dc; i++){ 19 ans[index++] = matrix[tr][i]; 20 } 21 } 22 else if(tc == dc){//只有一列 23 for(int i = tr; i <= dr; i++){ 24 ans[index++] = matrix[i][tc]; 25 } 26 } 27 else{//一般情况 28 int curC = tc; 29 int curR = tr; 30 while(curC != dc){//打印顶边 31 ans[index++] = matrix[tr][curC++]; 32 } 33 while(curR != dr){//打印右边 34 ans[index++] = matrix[curR++][dc]; 35 } 36 while(curC != tc){//打印底边 37 ans[index++] = matrix[dr][curC--]; 38 } 39 while(curR != tr){//打印左边 40 ans[index++] = matrix[curR--][tc]; 41 } 42 } 43 } 44 }

浙公网安备 33010602011771号