Accepted 8ms Java O(n) Time and Space complexity using HashMap


  • 0
    R
    public int[] twoSum(int[] nums, int target) {
            if(nums == null || nums.length == 0) return new int[0];
            int[] res = new int[2];
            Map<Integer, Integer> map = new HashMap<>();
            for(int i=0; i<nums.length; i++){
                Integer idx = map.get(target-nums[i]);
                if(null != idx){
                    res[0] = idx;
                    res[1] = i;
                    return res;
                }
                else{
                    map.put(nums[i], i);
                }
            }
            return new int[0];    
        }
    

Log in to reply
 

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