两个链表的第一个公共结点
题目描述:
输入两个链表,找出它们的第一个公共结点。(注意因为传入数据是链表,所以错误测试数据的提示是用其他方式显示的,保证传入数据是正确的)
解题思路:
设 A 的长度为 a + c,B 的长度为 b + c,其中 c 为尾部公共部分长度,可知 a + c + b = b + c + a。
当访问链表 A 的指针访问到链表尾部时,令它从链表 B 的头部重新开始访问链表 B;同样地,当访问链表 B 的指针访问到链表尾部时,令它从链表 A 的头部重新开始访问链表 A。这样就能控制访问 A 和 B 两个链表的指针能同时访问到交点。
算法实现:
public class Solution {
public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
ListNode p1 = pHead1 , p2 = pHead2;
while(p1 != p2){
p1 = (p1 == null) ? pHead2 : p1.next;
p2 = (p2 == null) ? pHead1 : p2.next;
}
return p1;
}
}
数字在排序数组中出现的次数
题目描述:
统计一个数字在排序数组中出现的次数。
解题思路:
利用二分查找,先找出数组中第一次出现该数字的索引first,再找出比该数大的第一个数的索引last,last-frist即为该数一共出现的次数。
算法实现:
public class Solution {
public int GetNumberOfK(int[] array, int K) {
int first = binarySearch(array, K);
int last = binarySearch(array, K + 1);
return (first == array.length || array[first] != K) ? 0 : last - first;
}
private int binarySearch(int[] array, int K) {
int l = 0, h = array.length ;
while (l < h) {
int m = ( l + h ) / 2;
if (array[m] >= K)
h = m;
else
l = m + 1;
}
return l;
}
}
二叉树的深度
题目描述:
输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。
思路分析:
用递归法求,先判断这棵树是否为空,如果为空,直接返回0,否则,递归求左子树和右子树的深度,返回Max(左子树深度,右子树深度)+1。
算法实现:
public class Solution {
public int TreeDepth(TreeNode root) {
if(root == null)
return 0;
int left = TreeDepth(root.left);
int right = TreeDepth(root.right);
return Math.max(left,right) + 1;
}
}
平衡二叉树
题目描述:
输入一棵二叉树,判断该二叉树是否是平衡二叉树。
思路分析:
平衡二叉树左右子树深度差不大于1,定义一个boolean类型的变量isBalanced用来判断是否是平衡二叉树,用递归的方法求出左右子树的深度,如果大于1,则isBalanced的值置位false,最后返回isBalanced。
算法实现:
public class Solution {
boolean isBalanced = true;
public boolean IsBalanced_Solution(TreeNode root) {
depth(root);
return isBalanced;
}
private int depth(TreeNode root){
if(root == null)
return 0;
int left = depth(root.left);
int right = depth(root.right);
if(Math.abs(left - right) > 1)
isBalanced = false;
return Math.max(left,right) + 1;
}
}
数组中只出现一次的数字
题目描述:
一个整型数组里除了两个数字之外,其他的数字都出现了两次。请写程序找出这两个只出现一次的数字。
思路分析:
异或的方法,将数组的所有元素进行异或得到的结果为不存在重复的两个元素异或的结果。diff &= -diff 得到出 diff 最右侧不为 0 的位,也就是不存在重复的两个元素在位级表示上最右侧不同的那一位,利用这一位就可以将原数组分为两组,一组‘1’,一组‘0’
两组数字再分别异或,最终两个结果就是数组中只出现一次的数字。
算法实现:
public class Solution {
public void FindNumsAppearOnce(int [] array,int num1[] , int num2[]) {
int diff = 0;
for(int arr : array)
diff ^= arr;
diff &= -diff;
for(int arr : array){
if((arr & diff) == 0)
num1[0] ^= arr;
else
num2[0] ^= arr;
}
}
}