int[] array = { 1, 2, 4, 5, 7, 8, 9, 6 }; int targetSum = 10; int[] expectedResult = TwoNumberSum_Solution0(array, targetSum); foreach (int item in expectedResult) { Console.WriteLine(item); }
Solution 1.
public static int[] TwoNumberSum_Solution0(int[] array, int targetSum) { for (int i = 0; i < array.Length - 1; i++) { int firstNum = array[i]; for (int j = i + 1; j < array.Length; j++) { int secondNum = array[j]; if (firstNum + secondNum == targetSum) { return new int[] { array[i], array[j] }; } } } return new int[0]; }
Solution 2
//using System.Collections.Generic; public static int[] TwoNumberSum(int[] array, int targetSum) { HashSetvisited = new HashSet (); foreach (int num in array) { int expectedResult = targetSum - num; if (visited.Contains(expectedResult)) { return new int[] { expectedResult, num }; } else { visited.Add(num); } } return new int[0]; }
Test case
{ "array": [4, 5, -4, 8, 12, 1, -2, 6], "targetSum": 10 } { "array": [4, 6], "targetSum": 10 } { "array": [4, 6, 1], "targetSum": 5 } { "array": [4, 6, 1, -3], "targetSum": 3 } { "array": [1, 2, 3, 4, 5, 6, 7, 8, 9], "targetSum": 17 } { "array": [1, 2, 3, 4, 5, 6, 7, 8, 9, 15], "targetSum": 18 } { "array": [-7, -5, -3, -1, 0, 1, 3, 5, 7], "targetSum": -5 } { "array": [-21, 301, 12, 4, 65, 56, 210, 356, 9, -47], "targetSum": 163 } { "array": [-21, 301, 12, 4, 65, 56, 210, 356, 9, -47], "targetSum": 164 } { "array": [3, 5, -4, 8, 11, 1, -1, 6], "targetSum": 15 } { "array": [14], "targetSum": 15 } { "array": [15], "targetSum": 15 }
No comments:
Post a Comment