Given an array
Example
Return
Solution
The problem can be solved with Hashing. We can maintain HashSet for the visited elements. While iteration we can do a lookup in visited HashSet for the current element with
Code
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
import java.util.*; public class DiffKII { public static void main(String[] args) { Integer a[] = { 1,5,3 }; int K=2; System.out.println(new DiffKII().diffPossible(Arrays.asList(a), K)); } public int diffPossible(final List<Integer> a, int K) { HashSet<Integer> visitedSet = new HashSet<Integer>(); for (Integer number : a) { //Do look up in previously visited element. if (visitedSet.contains(number + K) || visitedSet.contains(number - K)) return 1; //Maintaining Visited Element Set visitedSet.add(number); } return 0; } } |
Output
We encourage you to write a comment if you have a better solution or having any doubt on the above topic.
In this case output is 2 right.
such as
3 – 1 = 2 and 5-3 =2;
I have shared the sample code here,
private int diffPossible(List asList, int k) {
int count = 0 ;
HashSet visted = new HashSet();
for(Integer val : asList) {
if(visted.contains(val+ k) || visted.contains(val – k )){
count++;
}
visted.add(val);
}
return count;
}