Boolean -vs- boolean
Java provides both a Boolean
and a boolean
type; the difference being the first type is an Object
where as the second is just a value. Wherever possible, you should use a value type, for efficiency. Since you return a simple true
or false
result, boolean
is the correct return type to use:
...
boolean ans = solution(arr, k);
...
private static boolean solution(int[] arr, int k) {
...
Autoboxing
The java Collections need Object
s as keys and values. The Java language will automatically "box" and "unbox" values as required. You take advantage of autoboxing in map.put(k-v,true)
... The value k-v
is autoboxed as an Integer
and true
is autoboxed as Boolean.TRUE
.
Yet, when you retrieve the value from map
, you explicitly do the autoboxing yourself: map.get(Integer.valueOf(x))
. You could simply write map.get(x)
.
Map<K,V> -vs- Set
When you have a Map<K,V>
, it is expected that different values will be stored in the map (under one or more keys).
In this case, you are only ever storing Boolean.TRUE
(autoboxed from true
). Your map.get()
either returns Boolean.TRUE
, or it returns null
if no value was stored under that key. You explicitly test if it is equal to the former value, but you could have tested the value was not null
instead. Or more directly, you could test whether a value was stored under that key, and replace the complicated statement with simply:
if (map.containsKey(x)) { ... }
At this point, it should be clear we don't need a HashMap
. Simply a Set
of Integer
values.
final Set<Integer> set = new HashSet<>();
...
set.add(k-x);
...
if (set.contains(x)) {
...
Algorithm
As mentioned by hodisr, you need to take into account that the list of numbers may contain only one copy of the value x
which is exactly half of the target value (k/2
). With your code, you add k-x
to your container, and later successfully pull out the flag corresponding to x
, and declare true
.
Then, hodisr proceeds to demonstrate how to do it in one pass, and goes ahead and repeats the same error, by adding k-x
to the container before testing whether x
can be pulled out. To obtain the correct result, the check for x
must be made before putting k-x
into the container.
private static boolean solution(int[] arr, int k) {
Set<Integer> set = new HashSet<>();
for (int x : arr) {
if (set.contains(x))
return true;
set.add(k-x);
}
return false;
}