public class Solution { public int[] TwoSum(int[] numbers, int target) { Dictionary<int, int> dic = new Dictionary<int, int>(); int count = numbers.Count(); List<KeyValuePair<int, int>> list = new List<KeyValuePair<int, int>>(); for (int i = 0; i < count; i++) { if (!dic.ContainsKey(numbers[i])) { dic.Add(numbers[i], i); list.Add(new KeyValuePair<int, int>(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; } }
https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/#/description
补充一个“双指针”思想的解决方案,使用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+=1 10 11 return [i+1,j+1]
Java版:
1 class Solution { 2 public int[] twoSum(int[] numbers, int target) { 3 int l = numbers.length; 4 int i=0; 5 int j=l-1; 6 while(i < j){ 7 int cursum = numbers[i] + numbers[j]; 8 if(cursum < target){ 9 i++; 10 }else if(cursum > target){ 11 j--; 12 }else{ 13 return new int[]{i+1,j+1}; 14 } 15 } 16 return new int[]{0,0}; 17 } 18 }