//给定两个整形数组,寻找这两个数组的公有的且最大的元素
public class MaxCommonEle {
public static int findCommMax(int[] arr1, int[] arr2)
{
if(arr1 == null || arr2 == null)
throw new NullPointerException();
if(arr1.length == 0 || arr2.length == 0)
throw new IllegalArgumentException();
//build heap--大顶堆 , time complex: O(M)
for(int i = arr1.length / 2 -1; i >= 0; i--)
percDown(arr1, i, arr1.length);
//build heap, O(N)
for(int i = arr2.length / 2 - 1; i >= 0; i--)
percDown(arr2, i, arr2.length);
int len_1 = arr1.length - 1;
int len_2 = arr2.length - 1;
while(len_1 >= 0 && len_2 >=0)
{
int max1 = arr1[0];//获取大顶堆的根元素,即数组中的最大值
int max2 = arr2[0];
if(max1 > max2)//如果arr1的堆顶元素要大,则删除arr1的堆顶元素
{
swap(arr1, 0, len_1);//delete arr1‘s root
percDown(arr1, 0, len_1);//进行堆调整, 删除了最后一个元素,刚好堆调整的元素个数为 len_1
len_1--;
}
else if( max1 //如果arr2的堆顶元素要大,则删除arr2的堆顶元素
{
swap(arr2, 0, len_2);
percDown(arr2, 0, len_2);
len_2--;
}
else//arr1的堆顶元素与 arr2的堆顶元素相等了.
return max1;
}
return -1;// -1 means there are no common element
}
private static void percDown(int[] arr, int i, int n)
{
int tmp;
int child;
// int k = leftChild(i);
for(tmp = arr[i]; leftChild(i) child)
{
child = leftChild(i);
if(child != n-1 && arr[child] ])
child = child + 1;
if(tmp < arr[child])
arr[i] = arr[child];
else
break;
}
arr[i] = tmp;
}
private static int leftChild(int i){
return (i <<1 ) + 1;
}
private static void swap(int[] arr ,int i, int j)
{
int tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
//hapjin test
public static void main(String[] args) {
int[] arr1 = {8,2,9,6,18,7,25,28};
int[] arr2 = {6,39,4,9,25,18,36,12};
// int[] arr1 = {4,2,8};
// int[] arr2 = {10,4,6};
// int[] arr1 = {4,2,8};
// int[] arr2 = {5,7,9};
int res = findCommMax(arr1, arr2);
System.out.println(res);
}
}