提交网址: https://leetcode.com/problems/two-sum/
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.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
Case 2:
[2,3,11,3]
6
[1,3]
思路: 使用Dictionary<int, int>存储每一个整数在原输入中的下标,返回结果中下标从0开始算,需从小到大排列。特别要注意的是有相等数字的情形~
已AC代码:
public class Solution
{
public int[] TwoSum(int[] nums, int target)
{
int[] res = {0, 0};
int len = nums.Length;
Dictionary<int, int> dict = new Dictionary<int, int>();
for (int i = 0; i < len; i++)
{
int query = target - nums[i];
if (dict.ContainsKey(query))
{
int min = (i <= dict[query]) ? i : dict[query];
int max = (i <= dict[query]) ? dict[query] : i;
return new int[] { min, max };
}
else if (!dict.ContainsKey(nums[i]))
{
dict.Add(nums[i], i);
}
}
return res;
}
}