O(n) java solution. Easy to undestand 6 lines of code

  • 0
    public class Solution {
        public int[] twoSum(int[] nums, int target) {
            HashMap<Integer, Integer> m = new HashMap<Integer, Integer>();
            for(int i = 0; i<nums.length;i++){
                m.put(nums[i], i);
            for(int i=0; i<nums.length; i++){
                if(m.containsKey(target-nums[i]) && m.get(target-nums[i])!=i)
                    return new int[]{i, m.get(target-nums[i])};
            return new int[]{0};

  • 1

    This only works for the scenario that no duplicate integers in the array, for example, if the array is like {1, 2, 2, 100, 500}, the target value is 4, then the solution will fail.

  • 0

    this is correct, it has already considered the case you mentioned by

Log in to reply

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