Two Sum (Count)

Part I: Basic Version (Only one pair of solution)

public int[] twoSum(int[] nums, int target) {
        int[] ans = new int[2];

        // check corner case
        if (nums == null || nums.length == 0) {
            return ans;
        }

        HashMap<Integer, Integer> map = new HashMap<>();

        for (int i = 0; i < nums.length; i++) {
            if (map.containsKey(target - nums[i])) {
                ans[0] = i;
                ans[1] = map.get(target- nums[i]);
                break;
            } else {
                map.put(nums[i], i);
            }
        }

        return ans;
    }

Part II: Two Sum Count

    public int twoSumCount(int[] nums, int target) {
        if (nums == null || nums.length == 0) return 0;
        HashSet<Integer> set = new HashSet<>();

        // first pass, add all to hashset
        for (int num: nums) {
            set.add(num);
        }

        int count = 0;
        // second pass, find pairs
        for (int num: nums) {
            if (set.contains(target - num)) {
                count++;
            }
        }
        return count;
    }

results matching ""

    No results matching ""