Skip to content

Latest commit

 

History

History
86 lines (67 loc) · 2.05 KB

_1. Two Sum.md

File metadata and controls

86 lines (67 loc) · 2.05 KB

All prompts are owned by LeetCode. To view the prompt, click the title link above.

Back to top


First completed : May 22, 2024

Last updated : July 10, 2024


Related Topics : Array, Hash Table

Acceptance Rate : 53.83 %


Solutions

Java

// Slow and O(n^2)
// See alternative OTHER for hashmap solution

class Solution {
    public int[] twoSum(int[] nums, int target) {
        for (int i = 0; i < nums.length - 1; i++) {
            for (int j = i+1; j < nums.length; j++) {
                if (nums[i] + nums[j] == target) {
                    return new int[]{i, j};
                }
            }
        }

        return new int[]{};
    }
}
class Solution {
    public int[] twoSum(int[] nums, int target) {
        if (nums.length == 2) {
            return new int[]{0, 1};
        }

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

        for (int i = 0; i < nums.length; i++) {
            if (ref.containsKey(nums[i])) {
                return new int[]{ref.get(nums[i]), i};
            }
            ref.put((target - nums[i]), i);
        }

        // No solution (shouldn't occur given parameters provided)
        return new int[]{0, 0};
    }
}

Python

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        if len(nums) == 2 :
            return [0, 1]

        differences = {}
        for i in range(len(nums)) :
            if nums[i] in differences.keys() :
                return [i, differences.get(nums[i])]
            differences[target - nums[i]] = i
        return [0, 0]