C# 陣列中兩個元素相加 = 某值 求兩個元素的下標 + 字典問題
阿新 • • 發佈:2019-01-25
private int[] GetElement_Two(int[] arry, int target) { Dictionary<int, int> dict = new Dictionary<int, int>(); for (int i = 0; i < arry.Length; i++) { dict.Add(i, arry[i]); } for (int i = 0; i < arry.Length; i++) { int temp = target - arry[i]; if (dict.ContainsValue(temp)) { //這句程式碼是,根據value 取得 字典中第一次出現的對應鍵 //記得 using System.Linq; var firstKey = dict.FirstOrDefault(q => q.Value == temp).Key; return new int[] { i, firstKey}; } } throw new IllegalArgumentException("沒有滿足條件的值"); }