1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
| public int[] TwoSum(int[] nums, int target) { Dictionary<int,int> targetDic = new Dictionary<int,int>();
int left = 0, right = nums.Length - 1;
while (left <= right) { int targetNum = target - nums[left]; if (targetDic.ContainsKey(targetNum)) { return new int[] { left, targetDic[targetNum] }; } else { targetDic[nums[left]] = left; }
targetNum = target - nums[right]; if (targetDic.ContainsKey(targetNum)) { return new int[] { right, targetDic[targetNum] }; } else { targetDic[nums[right]] = right; }
left++; right--; }
return new int[] {0}; }
|