Do I have to assume that there are no duplicates in the input?


  • 0
    D

    nums: [3,2,4,4]
    target = 6

    Expected is [1,3]
    But it can be [1,2] also.

    In that case my solution was:
    // Make it efficient: O(n)
    // Making sure that duplicates are also included

    public class Solution {
    public int[] twoSum(int[] nums, int target) {
    int [] result = new int[2];

        Map<Integer, List<Integer>> map = new HashMap<>();
        
        for(int i = 0 ; i < nums.length ; i++) {
            if(map.containsKey(nums[i])) {
                map.get(nums[i]).add(i);
            } else {
                List<Integer> al = new ArrayList<>();
                al.add(i);
                map.put(nums[i], al);
            }
        }
        
        for(Integer key: map.keySet()) {
            int req = target - key;
            if(map.containsKey(req) &&
                (req != key || map.get(key).size() > 1)) {
                result[0] = map.get(key).get(0);
                result[1] = (key == req) ? map.get(key).get(1) : map.get(req).get(0);
                return result;
            }
        }
        
        return result;
    }
    

    }


  • 1
    Y

    There can be duplicates but there will be a unique solution. So if nums is [1,4,4] you could have a target of 8 but not a target of 5.


  • 0
    D

    @yorkshire Thanks for responding


Log in to reply
 

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