Without changing the outputs or the inputs of the method, how would you make this code more readable ?
I am interested in any general improvement it can be made in terms of readability without WORSEN the time complexity.
Above all I'm interested of know if there is a way of doing all this steps in one line:
check if the key exist in the map.
if exist create a list with two elements (pair) and then append the pair to list of pairs that will be the result.
if not exist do nothing.
Also is there a more elegant way to return array[][]
from an ArrayList<ArrayList<Integer>>
?
static int[][] findPairsWithGivenDifference(int[] arr, int k) {
int n = arr.length;
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
ArrayList<ArrayList<Integer>> all = new ArrayList<ArrayList<Integer>>();
for (int i = 0; i < n; i++){
map.put(arr[i]-k,arr[i]);
}
for (int i = 0; i < n; i++){
int x = arr[i];
if (map.get(arr[i]) != null) {
int y = map.get(x);
ArrayList<Integer> al = new ArrayList<Integer>();
al.add(y);
al.add(x);
all.add(al);
}
}
int m = all.size();
int[][] res = new int[m][2];
for (int i = 0; i < m; i++) {
for (int j = 0; j < 2; j++) {
res[i][j] = all.get(i).get(j);
}
}
return res;
}