21、leetcode回文链表、翻转图像

    科技2022-08-29  97

    面试题 02.06. 回文链表

    编写一个函数,检查输入的链表是否是回文的。 示例 1:

    输入: 1->2 输出: false

    示例 2:

    输入: 1->2->2->1 输出: true

    进阶:

    你能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题?

    我的答案

    /** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ class Solution { public boolean isPalindrome(ListNode head) { if(head==null){ return true; } int length=0; ListNode ne=head,pre=null; while(ne!=null){ length++; ne = ne.next; } if(length==1){ return true; }else if(length == 2){ return head.val==head.next.val; } for(int i=0;i<length/2;i++){ ne = head; head = head.next; ne.next = pre; pre = ne; } if(length%2!=0){ head = head.next; } while(ne!=null){ if(ne.val!=head.val){ return false; } ne = ne.next; head = head.next; } return true; } }

    832. 翻转图像

    给定一个二进制矩阵 A,我们想先水平翻转图像,然后反转图像并返回结果。 水平翻转图片就是将图片的每一行都进行翻转,即逆序。例如,水平翻转 [1, 1, 0] 的结果是 [0, 1, 1]。 反转图片的意思是图片中的 0 全部被 1 替换, 1 全部被 0 替换。例如,反转 [0, 1, 1] 的结果是 [1, 0, 0]。 示例 1:

    输入: [[1,1,0],[1,0,1],[0,0,0]] 输出: [[1,0,0],[0,1,0],[1,1,1]] 解释: 首先翻转每一行: [[0,1,1],[1,0,1],[0,0,0]]; 然后反转图片: [[1,0,0],[0,1,0],[1,1,1]]

    示例 2:

    输入: [[1,1,0,0],[1,0,0,1],[0,1,1,1],[1,0,1,0]] 输出: [[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,1,0]] 解释: 首先翻转每一行: [[0,0,1,1],[1,0,0,1],[1,1,1,0],[0,1,0,1]]; 然后反转图片: [[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,1,0]]

    说明:

    1 <= A.length = A[0].length <= 20 0 <= A[i][j] <= 1

    我的答案

    class Solution { public int[][] flipAndInvertImage(int[][] A) { int temp=0; for (int i = 0; i < A.length; i++) { for (int j = 0; j < A[0].length/2; j++) { temp = A[i][j]; A[i][j] = A[i][A[0].length-j-1]^1; A[i][A[0].length-j-1] = temp^1; } if(A[0].length%2==1){ A[i][A[0].length/2]^=1; } } return A; } }
    Processed: 0.016, SQL: 9