Can somebody review the code and provide suggestions on where I can improve on the code like use of better data structure etc.
Input: {1,7,2,8,3,6}, 9
Output: [0, 3] [1, 2] [4, 5]
public class TwoSumExactAll {
public static void main(String[] args) {
int[] nums1 = {1,7,2,8,3,6};
for (List<Integer> list : twoSumExactWithList(nums1,9)) {
System.out.println(list);
}
}
public static ArrayList<List<Integer>> twoSumExactWithList(int[] nums,int target) {
HashMap<Integer,Integer> map = new HashMap<Integer, Integer>();
ArrayList<List<Integer>> outerList = new ArrayList<List<Integer>>();
ArrayList<Integer> innerList=null;
int complement;
for(int i=0;i<nums.length;i++) {
complement = target-nums[i];
if(map.containsKey(complement)) {
innerList = new ArrayList<Integer>();
innerList.add(map.get(complement));
innerList.add(i);
outerList.add(innerList);
}else {
map.put(nums[i], i);
}
}
return outerList;
}
}