We will explore an efficient solution to the classic "Two Sum" problem using C#. Given an array of integers and a target value, our goal is to find the indices of two numbers that add up to the target. We will walk through a concise and optimized algorithm, accompanied by an implementation in C#.
Example:
Let's consider the following scenario to illustrate the Two Sum problem.
Given the array `nums = [2, 7, 11, 15]` and the `target = 9`,
we need to find two numbers in the array that add up to the target.
For the provided input, the expected output is indices = [0, 1], indicating that the numbers at indices 0 and 1 in the array nums (2 and 7, respectively) add up to the target value of 9.
Code Implementation:
public class Solution {
public int[] TwoSum(int[] nums, int target) {
Dictionary complementMap = new Dictionary();
int[] result = new int[2];
for (int i = 0; i < nums.Length; i++) {
int complement = target - nums[i];
if (complementMap.ContainsKey(complement)) {
result[0] = complementMap[complement];
result[1] = i;
return result;
}
else if (!complementMap.ContainsKey(nums[i])) {
complementMap.Add(nums[i], i);
}
}
return result;
}
}
Explanation:
- We start by initializing a dictionary called complementMap to store the complement of each number encountered in the array.
- We create a result array to hold the indices of the two numbers that add up to the target.
- Next, we iterate through the array using a for loop.
- For each number at index i, we calculate the complement by subtracting the current number from the target.
- We check if the complementMap contains the complement. If it does, we have found our solution.
- We assign the index of the complement (stored in the complementMap) to result[0].
- We assign the current index i to result[1].
- We return the result array.
- If the complement is not found in the complementMap, we check if the current number is already present as a key in the complementMap. If not, we add it to the complementMap with its index as the value.
- If no solution is found after iterating through the entire array, we return the default result array with both indices set to 0.