Simple Java Code using HashMap


  • 0
    A
    public class Solution {
        public int[] twoSum(int[] nums, int target) {
           int[] res = new int[2];
           if (nums == null || nums.length == 0){
               return res;
           }
           HashMap<Integer,Integer> hm = new HashMap<Integer,Integer>();
           for (int i = 0; i < nums.length; i++){
               if (hm.containsKey(target - nums[i])){
                   res[0] = hm.get(target - nums[i]);
                   res[1] = i;
                   return res;
               }
               else {
                   hm.put(nums[i],i);
               }
           }
           return res;
        }
    }

Log in to reply
 

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