Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].
Input: nums = [3,2,4], target = 6
Output: [1,2]
Input: nums = [3,3], target = 6
Output: [0,1]
public static int[] TwoSum_V1(int[] nums, int target) // Brute force Solution, time complexity of O(n^2)
{
for (int i = 0; i < nums.Length; i++) // outter loop of nums array
{
for (int j = 0; j < nums.Length; j++) // inner loop of nums array
{
if (nums[i] + nums[j] == target && i!=j) // if num[i] + num[j] == target, we found the required values
{
return new int[] { nums[j], nums[i] };
}
}
}
return null; // If no pair of numbers adds up to the target, return an empty array
}
public static int[] TwoSum_V2(int[] nums, int target) // Better Solution, time complexity of O(n)
{
Dictionary numIndices = new Dictionary(); // Create a dictionary to store the indices of each number
for (int i = 0; i < nums.Length; i++) // Iterate through the array
{
int complement = target - nums[i]; // Calculations
if (numIndices.ContainsKey(complement)) // if the dictionary contains the complement, we found the required values
{
return new int[] { nums[numIndices[complement]], nums[i]};
}
numIndices[nums[i]] = i; // Otherwise, add the current number to the dictionary
}
return null; // If no pair of numbers adds up to the target, return an empty array
}
Input: nums = [-1,-2,-3,-4,3,2,1]
Output: 1
Explanation: The product of all values in the array is 144, and signFunc(144) = 1
Input: nums = [1,5,0,2,-3]
Output: 0
Explanation: The product of all values in the array is 0, and signFunc(0) = 0
Input: nums = [-1,1,-1,1,-1]
Output: -1
Explanation: The product of all values in the array is -1, and signFunc(-1) = -1
public static int ArraySign(int[] nums)
{
int product = 1; // initialize product variable = 1
foreach (int num in nums) // multiply values or return 0 if 0 is found
{
if (num == 0)
return 0;
else
product *= num;
}
return SignFunc(product); // call SignFunc to determine the sign
}
public static int SignFunc(int x)
{
return (x > 0 ? 1 : -1); // equivalent to if(x>0) {return 1;} else {return -1;}
}