Solution #1
Since the original question only wants a simplified solution (and not a faster one), here is a one-line solution:
public boolean contains(int[] array, int key) {
return Arrays.toString(array).matches(".*[\\[ ]" + key + "[\\],].*");
}
Explanation: Javadoc of Arrays.toString()
states the result is enclosed in square brackets and adjacent elements are separated by the characters ", " (a comma followed by a space). So we can count on this. First we convert array
to a string, and then we check if key
is contained in this string. Of course we cannot accept "sub-numbers" (e.g. "1234" contains "23"), so we have to look for patterns where the key
is preceded with an opening bracket or a space, and followed by a closing bracket or a comma.
Note: The used regexp pattern also handles negative numbers properly (whose string representation starts with a minus sign).
Solution #2
This solution is already posted but it contains mistakes, so I post the correct solution:
public boolean contains(int[] array, int key) {
Arrays.sort(array);
return Arrays.binarySearch(array, key) >= 0;
}
Also this solution has a side effect: it modifies the array
(sorts it).