YangQG 面试题汇总
一、交叉链表
问题:
给你两个单链表的头节点 headA
和 headB
,请你找出并返回两个单链表相交的起始节点。如果两个链表不存在相交节点,返回 null
。
解题思想:
双指针
备注:不是快慢指针,如果两个长度相同可以用快慢指针,因为两个链表长度不同。
package org.example.YangQianGuan;class Node {int data;Node next;Node(int val) {this.data = val;this.next = null;}@Overridepublic String toString() {return " {data: " + this.data + " next: " + this.next + "} ";}
}public class IntersectionNode {public Node getStartInter(Node headA, Node headB) {if (headA == null || headB == null) {return null;}Node pA = headA;Node pB = headB;while (pA!= pB) {pA = pA == null? headB : pA.next;pB = pB == null? headA : pB.next;}return pA;}public static void main(String[] args) {// node listNode node8 = new Node(8);Node node4 = new Node(4);Node node5 = new Node(5);node8.next = node4;node4.next = node5;// A listNode headA = new Node(4);Node nodeA1 = new Node(1);headA.next = nodeA1;nodeA1.next = node8;// B ListNode headB = new Node(5);Node nodeB1 = new Node(6);Node nodeB2 = new Node(1);headB.next = nodeB1;nodeB1.next = nodeB2;nodeB2.next = node8;IntersectionNode intersectionNode = new IntersectionNode();Node startInter = intersectionNode.getStartInter(headA, headB);System.out.println(startInter);}
}
二、对称二叉树
Tree
package org.example.YangQianGuan;class Tree{int data;Tree left;Tree right;public Tree(int data, Tree left, Tree right) {this.data = data;this.left = left;this.right = right;}
}public class IsMirrorTree {public boolean isMirror(Tree root) {if (root == null) {return true;}return this.isMirrorCore(root.left, root.right);}public boolean isMirrorCore(Tree left, Tree right) {if (left == null && right == null) {return true;}if (left == null || right == null) {return false;}if (left.data != right.data) {return false;}return isMirrorCore(left.left, right.right) && isMirrorCore(left.right, right.left);}public static void main(String[] args) {Tree right4 = new Tree(3, null, null);Tree right3 = new Tree(4, null, null);Tree right2 = new Tree(2, right3, right4);Tree left4 = new Tree(4, null, null);Tree left3 = new Tree(3, null, null);Tree left2 = new Tree(2, left3, left4);Tree node1 = new Tree(1, left2, right2);IsMirrorTree isMirrorTree = new IsMirrorTree();boolean mirror = isMirrorTree.isMirror(node1);System.out.println(mirror);}}
三、轮转数组
package org.example.YangQianGuan;import java.util.Arrays;
import java.util.List;public class RightRunArr {public static void main(String[] args) {int[] nums = {1, 2, 3, 4, 5, 6, 7};int n = 3;RightRunArr rightRunArr = new RightRunArr();int[] core = rightRunArr.core(nums, n);System.out.println(Arrays.toString(core));}private int[] core(int[] nums, int n) {int[] res = new int[nums.length];int bit = n % nums.length;System.out.println(bit);int[] left = Arrays.copyOfRange(nums, 0, nums.length - bit);int[] right = Arrays.copyOfRange(nums, nums.length - bit, nums.length);int i = 0;for (int i1 : right) {res[i] = i1;i++;}for (int i1 : left) {res[i] = i1;i++;}return res;}
}