两个升序数组合并成一个数组的算法
有两个数组,a[]、b[],都是已经升序排好序的,现将两个数组合成一个数组c[],要求时间复杂度是O(n),注意边界情况。
public static int[] getNewArray(int a[], int b[]) {
int c[] = new int[a.length + b.length];
int ai = 0;int bi = 0; int ci = 0;
while (ai < a.length || bi < b.length) {
if (ai < a.length && bi < b.length) {
if (a[ai] < b[bi]) {
c[ci] = a[ai];
ai++;
} else {
c[ci] = b[bi];
bi++;
}
ci++;
}
if (ai == a.length) {
c[ci] = b[bi];
bi++;
ci++;
}
if (bi == b.length) {
c[ci] = a[ai];
ai++;
ci++;
}
}
return c;
}
public static void main(String[] args) {
int a[] = { 1, 3, 5, 7, 14, 25, 26, 31, 34, 46, 56, 63, 66, 74 };
int b[] = { 1, 2, 5, 23, 24, 33 };
int c[] = getNewArray(a, b);
System.out.println(c[8]);
// for (int i = 0; i < c.length; i++) {
// System.out.print(c[i] + ",");
// }
}
二叉树中两个节点的最近公共父节点
https://www.cnblogs.com/neuzk/p/9487301.html
思想:假设根结点为root,其中给定的两个结点分别为A和B,它们分别都不为null。如果当前结点p为null,那么直接返回null,如果当前结点p是给定的结点中的其中一个结点,那么直接返回当前结点p(如果p是根结点,程序一次就返回了,下面的递归也不会出现)。如果当前节点不是A和B中的一个,那么需要分别去查找p的左右子树,看看是否包含A或者B,查询左右子树后,如果查询左子树和查询右子树的结果都不为null,说明当前结点p就是最近的公共祖先。否则,如果查询左子树结果为null,那么返回查询右子树的结果。反之,返回查询左子树的结果。
public static TreeNode getParent(TreeNode root, TreeNode node1,TreeNode node2) { if(root == null || node1 == null || node2 == null) return null; //这里可以换成if(root == node1 || root == node2),我只是为了方便测试才这样写 if(root.val == node1.val || root.val == node2.val) return root; TreeNode left = getParent(root.left,node1,node2); TreeNode right = getParent(root.right,node1,node2); //如果左右子树都能找到,那么当前节点就是最近的公共祖先节点 if(left != null && right != null) return root; //如果左子树上没有,那么返回右子树的查找结果 if(left == null) return right; //否则返回左子树的查找结果 else return left; } |
二分查找
O(logn)
/** * 使用递归的二分查找 *title:recursionBinarySearch *@param arr 有序数组 *@param key 待查找关键字 *@return 找到的位置 */ public static int recursionBinarySearch(int[] arr,int key,int low,int high){
if(key < arr[low] || key > arr[high] || low > high){ return -1; }
int middle = (low + high) / 2; //初始中间位置 if(arr[middle] > key){ //比关键字大则关键字在左区域 return recursionBinarySearch(arr, key, low, middle - 1); }else if(arr[middle] < key){ //比关键字小则关键字在右区域 return recursionBinarySearch(arr, key, middle + 1, high); }else { return middle; }
} |