JAVA Solution for two-sum


  • 0
    S
    public int[] twoSum(int[] nums, int target) {
        HashMap<Integer, Integer> map = new HashMap<>();
        int[] result = new int[2];
        for(int i = 0; i < nums.length; i++){
            if(map.containsKey(nums[i]))
            {
                result[0] = map.get(nums[i]);
                result[1] = i;
                return result;
            }
            else
                map.put(target - nums[i], i);    
        }
        return result;
    }

  • 0
    J

    @sb90 This solution is throwing an exception when the array has a number repeating itself. I've pasted the test case that failed below. The number 863 (at index 1 and 40) repeats itself and the hashtable throws an exception.

    {230,863,916,585,981,404,316,785,88,12,70,435,384,778,887,755,740,337,86,92,325,422,815,650,920,125,277,336,221,847,168,23,677,61,400,136,874,363,394,199,863,997,794,587,124,321,212,957,764,173,314,422,927,783,930,282,306,506,44,926,691,568,68,730,933,737,531,180,414,751,28,546,60,371,493,370,527,387,43,541,13,457,328,227,652,365,430,803,59,858,538,427,583,368,375,173,809,896,370,789} target = 542


  • 0
    J

    @jsrikrish Quick Note, I've tried it in C# though. The same code you used works using Java.


  • 0
    S

    @jsrikrish Oh! I do not know C#. Is it because of the way the array is allocated?


  • 0
    J

    @sb90 I guess the difference was with the data structure used. I was going through some links..
    http://stackoverflow.com/questions/1669885/what-happens-when-a-duplicate-key-is-put-into-a-hashmap

    I didn't know you can add the same key with a value to a hashmap that was already added to it. According to the above link.. the most recent value is stored.
    For this question.. I think just storing the key is more important, because there could be multiple correct answers and the LOJ accepts any of the answers.

    I was using a dictionary for this implementation.. and it throws an exception if you try to add a key that already exists. In any case.. I eventually came up with a solution that just checked for the key value.. and didn't care which 'index' was being stored as value.

    Hope this helps.


Log in to reply
 

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