简体   繁体   中英

Java : Taking 2 array find if the element that exists in both array return true if exist else false

I am looking for some clarification on this solution. Can anyone guide me on the following two points:

  1. Is the below algorithm good solution?
  2. and is my Big O calculation correct?

your clarification is highly appreciated. Thanks in advance

public static void main(String[] args) {
    String[] a = {"a", "b", "c", "d"};
    String[] b = {"z", "f", "c"};

    boolean value1 = find(a, b);
    System.out.println(value1);

    boolean value2 = findArray(a, b);
    System.out.println(value2);

}

/*
since the both the array is of diff size for nested loop
Big O  = O(n*n)
if array size is same Big O = O(n^2)
 */
private static boolean find(String[] a, String[] b) {
    for (int i = 0; i < a.length; i++) {
        String val1 = a[i];
        for (int j = 0; j < b.length; j++) {
            if (val1.equals(b[j])) {
                System.out.println(val1 + " : " + b[j]);

                return true;
            }
        }// O(n)
    }// O(n)
    return false;
}// O(n*n)

/*
Big O  = O(n)
 */
private static boolean findArray(String[] a, String[] b) {
    //create array list from array
    List<String> list = new ArrayList<>(Arrays.asList(b));
    for (int i = 0; i < a.length; i++) {
        String val1 = a[i]; //O(1)

        if (list.contains(val1)) {
            System.out.println(val1 + " : contain in list b");
            return true;
        }// O(1)

    }// O(n)
    return false;
}// O(n)

Your second solution is also O(N^2), because contain works O(N) under the hood.

First Solution O(N*LogN):

  1. Sort second array. NLogN
  2. Iterate throught first one O(N) and binary search via second one O(logN) => O(NLogN)

Overall complexity O(NLogN)

Second solution O(N) - if arrays are sorted. If not O(NLogN), because of step 1

  1. Sort both of arrays O(NlogN)
  2. Do something like this

Code:

int curA = 0, curB = 0;
while (true) {
 if (curA >= a.length || curB >= b.length)
  break;
 if (a[curA] < b[curB]) {
  curA++;
  continue;
 }

 if (a[curA] > b[curB]) {
  curB++;
  continue;
 }

 return true;
}
return false;
  1. I think that both algorithms looks reasonable.
  2. ArrayList.contains time complexity is O(n).

The size, isEmpty, get, set, iterator, and listIterator operations run in constant time. The add operation runs in amortized constant time, that is, adding n elements requires O(n) time. All of the other operations run in linear time (roughly speaking). The constant factor is low compared to that for the LinkedList implementation.

https://docs.oracle.com/javase/6/docs/api/java/util/ArrayList.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM