My O(n) java solution using hashmap


  • 0
    S

    public class Solution {

    public int[] twoSum(int[] nums, int target) {
        if (nums.length <= 1) {
            return null;
        }
        int[] result = new int[2];
        Map<Integer, List<Integer>> hold = new HashMap<Integer, List<Integer>>();
        for (int i = 0; i < nums.length; i++) {
            List<Integer> temp;
            if (!hold.containsKey(nums[i])) {
                temp = new LinkedList<Integer>();
            } else {
                temp = hold.get(nums[i]);
            }
            temp.add(i);
            hold.put(nums[i], temp);
        }
        for (int key : hold.keySet()) {
            if (hold.containsKey(target - key)) {
                int a,b;
                if (key != target - key) {
                    a = hold.get(key).get(0) + 1;
                    b = hold.get(target - key).get(0) + 1;
                } else {
                    a = hold.get(key).get(0) + 1;
                    b = hold.get(key).get(1) + 1;
                }
                if (a < b) {
                    result[0] = a;
                    result[1] = b;
                } else {
                    result[0] = b;
                    result[1] = a;
                }
                return result;
            }
        }
        return null;
    }
    

    }

    I just get it worked alright. But I am not sure that if there is any more efficient way to handle it.
    Any feedback will be appreciated!


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.