Find the maximum value of common elements in two integer arrays

Source: Internet
Author: User
Tags sorts

one, The problem description

Given two integer arrays, find the largest common element in the two arrays. Note Condition: ① common element ② the largest public element

For example: arr1={8,2,9,6,18,7, arr2={6,39,4,9, 18,36,12}.Assume that the length of the arr1 is m,arr2 length is n

The maximum common elements of these two arrays Are: 25

second, the idea

① to each element in arr1 arr1[i], go arr2 Find out if the element also exists, if it exists, it is marked because it is public, but not necessarily the Largest.

Until all elements in the arr1 have been scanned, the time complexity is O (MN) and the space complexity is O (1)

② first sorts the array arr1, and then sorts the arr2. Define two pointers i, J points to the last element in arr1 and arr2, respectively. Compares the last element in the two arrays, finds the desired element if it is equal, and moves the pointer to the larger element forward by one (minus 1).

Sorting time complexity is O (MLOGM + nlogn), The worst case is the time complexity of the pointer traversal o (m+n), so the total time complexity is O (mlogm+nlogn)

③ uses heaps to implement

Two arrays are constructed of two large top stacks, and if the top elements of the heap are the same, the top element of the heap is the public largest element. otherwise, Delete the larger heap top element and make the heap adjustments to continue the Comparison.

The time complexity of the array 1 build heap is O (M), and the time complexity of the array 2 building is O (N)

generally, The time complexity is O (1) on average for the removal of heap top elements and for heap Adjustments. therefore, the time complexity should be smaller than the method ② on Average.

In addition, heap operations can be done directly on the original array, where the space complexity is O (1)

third, Method ③ Code implementation

The core code is as Follows:

1         intlen_1 = arr1.length-1;2         intLen_2 = arr2.length-1;3          while(len_1 >= 0 && len_2 >=0)4         {5             intMAX1 = arr1[0];//gets the root element of the large top heap, which is the maximum value in the array6             intMAX2 = arr2[0];7             8             if(max1 > Max2)//if the heap top element of the arr1 is larger, the top element of the arr1 is deleted9             {TenSwap (arr1, 0, len_1);//Delete arr1 ' s root onePercdown (arr1, 0, len_1);//Heap adjustment, Delete the last element, just the number of elements of the heap adjustment is len_1 alen_1--; -             } -             Else if(max1 < Max2)//if the heap top element of the ARR2 is larger, the top element of the ARR2 is deleted the             { -Swap (arr2, 0, len_2); -Percdown (arr2, 0, len_2); -len_2--; +             } -             Else//the top element of the arr1 is equal to the top element of the arr2 heap. +                 returnmax1; a}

When building a heap of two large tops, compare the top elements of these two big top heaps, who are large, then delete who. of course, after removing the heap top elements, heap adjustments are required to ensure the nature of the heap.

The Swap method on line 10th means that the top element of the heap is deleted, and the Percdown method on line 11th represents the heap Adjustment.

Delete the top element of the heap continuously until: ① the elements in a heap have been deleted (while the loop condition is not established) This indicates that there are no common elements in two arrays.

② if the heap top element of the two heap is the same (第20-21 row), it indicates that the largest common element was found.

The correctness of the algorithm is explained by the fact that the large top heap is Used. the top element of the heap must be the largest element in the current array, and by comparing the two top elements of the heap, if not equal, the larger heap top element is deleted , which always guarantees that the same and largest element in the two heap is first found.

Complete code implementation:

//given two shaped arrays, look for the public and largest elements of the two arrays public classMaxcommonele { public Static intFindcommmax (int[] arr1,int[] Arr2) {        if(ARR1 = =NULL|| ARR2 = =NULL)            Throw NewNullPointerException (); if(arr1.length = = 0 | | arr2.length = = 0)            Throw Newillegalargumentexception (); //build Heap--big Top heap, time Complex:o (M)             for(inti = arr1.length/2-1; I >= 0; i--) Percdown (arr1, i, arr1.length); //build heap, O (N)         for(inti = arr2.length/2-1; I >= 0; i--) Percdown (arr2, i, arr2.length); intlen_1 = arr1.length-1; intLen_2 = arr2.length-1;  while(len_1 >= 0 && len_2 >=0)        {            intMAX1 = arr1[0];//gets the root element of the large top heap, which is the maximum value in the array            intMAX2 = arr2[0]; if(max1 > Max2)//if the heap top element of the arr1 is larger, the top element of the arr1 is deleted{swap (arr1,0, len_1);//Delete arr1 ' s rootPercdown (arr1, 0, len_1);//Heap adjustment, Delete the last element, just the number of elements of the heap adjustment is len_1len_1--; }            Else if(max1 < Max2)//if the heap top element of the ARR2 is larger, the top element of the ARR2 is deleted{swap (arr2,0, len_2); Percdown (arr2,0, len_2); Len_2--; }            Else//the top element of the arr1 is equal to the top element of the arr2 heap.                returnmax1; }        return-1;//-1 means there is no common element    }        Private Static voidPercdown (int[] arr,intIintN) {inttmp; intchild ; //int k = Leftchild (i);         for(tmp = arr[i]; Leftchild (i) < n; i =child ) { child=Leftchild (i); if(child! = n-1 && arr[child] < arr[child+1]) child= child + 1; if(tmp <arr[child]) arr[i]=arr[child]; Else                 break; } arr[i]=tmp; }        Private Static intLeftchild (intI) {        return(i << 1) + 1; }        Private Static voidSwapint[] arr,intIintJ) {intTMP =arr[i]; arr[i]=arr[j]; arr[j]=tmp; }            //Hapjin Test     public Static voidmain (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};        intres =Findcommmax (arr1, arr2);    System.out.println (res); }}
View Code

four, references

Data Structure--deep Analysis of the implementation of heap

SortThe algorithm summarizes Heap Sort

Find the maximum value of common elements in two integer arrays

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.