2ms Java solution beats 100% of submissions


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

Log in to reply
 

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