public class Solution { public int[] TwoSum(int[] numbers, int target) { Dictionarydic = new Dictionary (); int count = numbers.Count(); List > list = new List >(); for (int i = 0; i < count; i++) { if (!dic.ContainsKey(numbers[i])) { dic.Add(numbers[i], i); list.Add(new KeyValuePair (numbers[i], i)); } } int[] ary = new int[2]; for (int i = 0; i < list.Count; i++) { for (int j = i; j < list.Count; j++) { var d1 = list[i]; var d2 = list[j]; if (d1.Key + d1.Key == target && d2.Value - d1.Value > 1) { ary[0] = d1.Value + 1; ary[1] = d1.Value + 2; return ary; } else if (i != j && d1.Key + d2.Key == target) { ary[0] = d1.Value + 1; ary[1] = d2.Value + 1; return ary; } } } return ary; }}
补充一个“双指针”思想的解决方案,使用python实现:
1 class Solution: 2 def twoSum(self, numbers: 'List[int]', target: 'int') -> 'List[int]': 3 i=0 4 j=len(numbers)-1 5 while numbers[i] + numbers[j] != target: 6 if numbers[i] + numbers[j]>target: 7 j-=1 8 else: 9 i+=110 11 return [i+1,j+1]