Untitled

mail@pastecode.io avatar
unknown
java
2 years ago
1.3 kB
2
Indexable
Never
import java.util.Hashtable;
import java.util.Map;

class Solution {
    public int[] twoSum(int[] nums, int target) {
        Hashtable<Integer, Integer> indexTable = new Hashtable<>();
        Hashtable<Integer, int[]> dupTable = new Hashtable<>();

        Hashtable<Integer, Integer> solution = new Hashtable<>();

        int [] myIndices = new int [2];

        for (int i =0; i<nums.length; ++i) {
           if (!(indexTable.contains(nums[i])))   {
                indexTable.put(nums[i], i);
           }
           else {
               int [] myNewArr = new int[1];
               myNewArr[myNewArr.length-1] = i; 
               dupTable.put(nums[i], myNewArr);
           }
        }

        for (int j = 0; j<nums.length; ++j) {
            int diff = target - nums[j];
            if (indexTable.contains(diff)) {
              if (indexTable.get(diff) != j) {
                  if (!(solution.contains(j))) 
                        solution.put(indexTable.get(diff), j);
              }
            }
        }

        for (Map.Entry<Integer, Integer> map : solution.entrySet()) {
            myIndices[0] = map.getKey();
            myIndices[1] = map.getValue();
        }
        return myIndices;
    }
}