Kenoru

TwoSum

Feb 22nd, 2021
814
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.14 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3.  
  4. namespace TwoSum
  5. {
  6.     class Program
  7.     {
  8.         static void Main(string[] args)
  9.         {
  10.             int[] array1 = { 2, 7, 11, 15 };
  11.             int target1 = 9;
  12.             (int first1, int second1) = new TwoTermsFinder().FindIndexes(array1, target1);
  13.             Console.WriteLine($"Two terms have indexes {first1} and {second1}");
  14.  
  15.             int[] array2 = { 13, 7, 9, 1, 11, 18 };
  16.             int target2 = 19;
  17.             (int first2, int second2) = new TwoTermsFinder().FindIndexes(array2, target2);
  18.             Console.WriteLine($"Two terms have indexes {first2} and {second2}");
  19.         }
  20.     }
  21.  
  22.     class TwoTermsFinder
  23.     {
  24.         Dictionary<int, int> number_index = new Dictionary<int, int>();
  25.         public (int, int) FindIndexes(int[] array, int target)
  26.         {
  27.             for(int i = 0; i < array.Length; i++)
  28.             {
  29.                 if (number_index.ContainsKey(target - array[i]))
  30.                     return (number_index[target - array[i]], i);
  31.                 number_index.Add(array[i], i);
  32.             }
  33.             return (0, 0);
  34.         }
  35.     }
  36. }
  37.  
Advertisement
Add Comment
Please, Sign In to add comment