-1- The brute-force method takes O(m*n) time (an O(m) linear search n times).
use the brute-force approach - for each element in one array, check if the element exists in the second array by looping thru it
-2- second method takes O(m log m) to sort, plus O(n log m) to search.
construct a binary search tree using the first array and do a look up with the elements in the second array
-3- sort both arrays, then step through them both simultaneously
O(m log m + n log n) for the sorts, and O(m + n) to step through afterwards.
- // start with arrays a and b.
- sort(a); // log(a.length) time
- sort(b); // log(b.length) time
- int aindex = 0;
- int bindex = 0;
- while (aindex < a.length && bindex < b.length) {
- if (a[aindex] == b[bindex]) {
- print(a[aindex] + " is in both a and b.");
- aindex++;
- bindex++;
- }
- else if (a[index] < b[bindex]) {
- aindex++;
- }
- else {
- bindex++;
- }
- }
-4- using a hashtable of some sort (e.g. HashSet), such that the whole process is O(m) to store the first array, and O(n) to check the contents of the second.
- import java.util.HashSet;
- import java.util.Set;
- public class IntIntersection {
- public static void main(String[] args) {
- int[] firstInts = new int[]{2,3,4,5,5,7,9,0,0,0};
- int[] secondInts = new int[]{2,44,2,33,8,5,12,14,0};
- Set<Integer> intersects = intersectArrays(firstInts, secondInts);
- // print out the set of intersecting intergers
- for (Integer theInt : intersects) {
- System.out.println("intersect on " + theInt);
- }
- }
- public static Set<Integer> intersectArrays(int[] first, int[] second) {
- // initialize a return set for intersections
- Set<Integer> intsIntersect = new HashSet<Integer>();
- // load first array to a hash
- HashSet<Integer> array1ToHash = new HashSet<Integer>();
- for (int i = 0; i < first.length; i++) {
- array1ToHash.add(first[i]);
- }
- // check second array for matches within the hash
- for (int i = 0; i < second.length; i++) {
- if (array1ToHash.contains(second[i])) {
- // add to the intersect array
- intsIntersect.add(second[i]);
- }
- }
- return intsIntersect;
- }
- }
If use python,
we can first set(list1), and set(list2)
find whether there is intersection with two sets:
use the following two functions, or just go through the smaller set and check whether its element also in set2
return [e for e in set1 if e in set2]
if the new list is not empty.
- isdisjoint(other)¶
- Return True if the set has no elements in common with other. Sets are disjoint if and only if their intersection is the empty set.
- intersection(other, ...)¶
- set & other & ...
- Return a new set with elements common to the set and all others.
int arr[] = { 1, 2, 3, 4, 5, 6 };
int size = sizeof( arr ) / sizeof( arr[0] );
cout << size << endl;
---- get the str length ----
char text[100] = "";
strcpy( text, "John" );
int len = (int) strlen( text );
cout << len << endl;
♥ ¸¸.•*¨*•♫♪♪♫•*¨*•.¸¸♥
http://www.coderanch.com/t/35439/Programming/Intersection-two-arrays
No comments:
Post a Comment