You will be given an integer k and a list of integers. Count the number of distinct valid pair of integers (a,b) in the list for which a+k=b.
For example, the array [1,1,1,2] has two different valid pairs:(1,1) and (1,2). Note that the three possible instances od pair (1,1) count as a single valid pair, as do the three possible instances of the pair (1,2). if k=1, then this means we have total of one 1 valid pair which satisfies a+k=b=>1+1=2, the pair (1,2).
My code:
public class PairArrayStream {
public static void main(String[] args) {
int k =1;
List<Integer> input = Arrays.asList(1,1,1,2);
HashSet<HashSet> hs = new HashSet<HashSet>();
IntStream.range(0, input.size())
.forEach(i -> IntStream.range(0, input.size())
.filter(j -> i != j && input.get(i) - input.get(j) == k)
.forEach(j -> {
HashSet inner = new HashSet<>();
inner.add(input.get(j));
inner.add(input.get(i));
hs.add(inner);
})
);
System.out.println("OutPut "+hs.size());
}
}
Without java 8 features::
int k =1;
List<Integer> input = Arrays.asList(1,1,1,2);
HashSet<HashSet> hs = new HashSet<HashSet>();
for(int i =0 ; i<numbers.size();i++){
for(int j = i; j<numbers.size();j++){
if(Math.abs(numbers.get(j)-numbers.get(i)) == k){
HashSet inner = new HashSet<>();
inner.add(numbers.get(j));
inner.add(numbers.get(i));
hs.add(inner);
}
}
}
Well, I am getting the correct output but 40% of the test cases gives me a timeout. Opinions and tactics are welcomed to make the code better and fast.