
Sponsored
Sponsored
This approach leverages a hash map (or dictionary) to solve the problem efficiently. By taking advantage of the average O(1) time complexity for insert and lookup operations in hash maps, we can create a mapping between elements and their indices (or frequencies, depending on the problem requirements). This method not only offers efficient retrieval but also makes it easier to track elements as we iterate through the data structure.
Time Complexity: O(n), where n is the number of elements in the input list.
Space Complexity: O(n), due to the storage of numbers in the hash map.
using System.Collections.Generic;
public class Solution {
public int[] TwoSum(int[] nums, int target) {
Dictionary<int, int> numMap = new Dictionary<int, int>();
for (int i = 0; i < nums.Length; i++) {
int complement = target - nums[i];
if (numMap.ContainsKey(complement)) {
return new int[] { numMap[complement], i };
}
numMap[nums[i]] = i;
}
return new int[] {};
}
}This C# solution uses a Dictionary to map numbers to their indices. Like the other implementations, it calculates the complement and uses the dictionary to check for its presence, returning indices if found.
This approach utilizes a two-pointer technique which is particularly effective when the input is sorted (or can be sorted) without significantly impacting performance. By using two pointers to traverse the array from both ends, we can efficiently find the pair of elements that sum to the target. Note that this approach is based on the assumption that sorting the input is feasible and will not exceed time limits.
Time Complexity: O(n log n) due to sorting.
Space Complexity: O(n) because we store tuples of indices and numbers.
1using System;
2using System.Linq;
3
4public class Solution {
5 public int[] TwoSum(int[] nums, int target) {
6 var numsWithIndex = nums.Select((num, index) => new { num, index }).ToArray();
7 Array.Sort(numsWithIndex, (a, b) => a.num.CompareTo(b.num));
8 int left = 0, right = numsWithIndex.Length - 1;
9 while (left < right) {
10 int sum = numsWithIndex[left].num + numsWithIndex[right].num;
11 if (sum == target) {
12 return new int[] { numsWithIndex[left].index, numsWithIndex[right].index };
13 } else if (sum < target) {
14 left++;
15 } else {
16 right--;
17 }
18 }
19 return new int[] {};
20 }
21}In this C# solution, the numbers and their indices are paired using LINQ and then sorted. Two pointers are then managed to detect the target pair.