LeetCode Two Sum Problem Solution



Sure, here's an example solution to the Two Sum problem on LeetCode in several programming languages:


1. **Python**:

class Solution(object):
    def twoSum(self, nums, target):
        num_indices = {}

        for i, num in enumerate(nums):
            complement = target - num
            if complement in num_indices:

                return [num_indices[complement], i]
            
            num_indices[num] = i

        return []
```

2. **Java**:
```java

public int[] twoSum(int[] nums, int target) { HashMap<Integer,Integer> map = new HashMap<>(); int [] ans = new int [2]; for(int i= 0 ;i<nums.length ;i++){ if(map.containsKey(target-nums[i])){ ans[0]= map.get(target-nums[i]); ans[1]= i; } map.put(nums[i],i); } return ans; }

3. **C++**:
  • class Solution {
    public:
        vector<int> twoSum(vector<int>& nums, int target) {
            unordered_map<int, int> m;
            for (int i = 0;; ++i) {
                int x = nums[i];
                int y = target - x;
                if (m.count(y)) {
                    return {m[y], i};
                }
                m[x] = i;
            }
        }
    };


```

These examples provide solutions to the Two Sum problem on LeetCode in Python, Java, C++, and JavaScript. Each solution uses a hashmap to store the indices of elements and their complements, iterating through the array to find the two numbers that sum up to the target value.

0 Comments