TwoSum

  • 105
  • 0
  • C#
  • 2024-07-10

演算法LeetCode TwoSun

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.


 

static void Main(string[] args)
       {
           int[] numbers = new[] {3, 21, 9, 5};
           int targetNumber = 8;
           
           var res = TwoSum(numbers, targetNumber);
           
           Console.WriteLine($"索引值:{string.Join(",", res)}");
           Console.WriteLine($"索引對應的值:{numbers[res[0]]} {numbers[res[1]]}");
           Console.ReadLine();
           
           int[] TwoSum(int[] nums, int target)
           {
               var dictionary = new Dictionary<int, int>();
               for (int i = 0; i < nums.Length; i++)
               {
                   var num = target - nums[i];
                   if (dictionary.ContainsKey(num))
                   {
                       return new int[] { dictionary[num], i };
                   }
                   //加入到dictionary,key為nums
                   dictionary[nums[i]] = i;
               }
               throw new ArgumentException("nums無匹配的2個值,滿足target");
           }
       }