Created
August 29, 2016 14:59
-
-
Save nichtemna/93a1a6dde6fca9c847b4c7948b64cd90 to your computer and use it in GitHub Desktop.
Find the smallest common element in two arrays
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.*; | |
/** | |
* Find the smallest common element in two arrays , if no return -1. Algorithm works in a linear time | |
*/ | |
public class SmallestCommon { | |
public static void main(String[] args) { | |
Scanner scanner = new Scanner(System.in); | |
int n = scanner.nextInt(); | |
int[] arr1 = new int[n]; | |
int[] arr2 = new int[n]; | |
for (int i = 0; i < n; i++) { | |
arr1[i] = scanner.nextInt(); | |
} | |
for (int i = 0; i < n; i++) { | |
arr2[i] = scanner.nextInt(); | |
} | |
System.out.println(getCommonLesser(arr1, arr2)); | |
} | |
private static int getCommonLesser(int[] arr1, int[] arr2) { | |
int result = -1; | |
Map<Integer, Integer> map = new HashMap<>(arr1.length); | |
for (int i : arr1) { | |
map.put(i, 1); | |
} | |
for (int i : arr2) { | |
if (map.containsKey(i)) { | |
map.put(i, 2); | |
} | |
} | |
List<Integer> list = new ArrayList<>(); | |
for (Map.Entry<Integer, Integer> entry : map.entrySet()) { | |
if (entry.getValue() == 2) { | |
list.add(entry.getKey()); | |
} | |
} | |
if (list.size() > 0) { | |
int smallest = list.get(0); | |
for (Integer i : list) { | |
if (i < smallest) { | |
smallest = i; | |
} | |
} | |
result = smallest; | |
} | |
return result; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment