Simple Java implementation


  • 3
    M
    public class Solution {
        public int[] twoSum(int[] nums, int target) {
            int[] ans = null;
            Map<Integer, Integer> valueIndex = new HashMap<>();
            for (int i = 0; i < nums.length; ++i) {
                Integer index = valueIndex.get(target - nums[i]);
                if (index == null) {
                    valueIndex.put(nums[i], i);
                } else {
                    ans = new int[] {index, i};
                    break;
                }
            }
            return ans;
        }
    }

Log in to reply
 

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