原题链接: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.
Example:
Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].思路1:
两重循环,暴力解法,时间复杂度: O(N^2)
思路2:
O(nlogn)思路(代替O(n^2的暴力解法brute solution)):
1 排序;
2 双指针,一头一尾;
3 if(sum<target),左指针右移
4 if(sum>target), 右指针左移
难点小结:
1 思路别错,n^2解法会超时
2 已知value,求key,需要点技巧
C# 代码:
public static int[] TwoSum(int[] nums, int target)
{
Dictionary<int, int> srcDic = new Dictionary<int, int>();
//记录key、value
for (int q = 0; q < nums.Count(); q++)
{
srcDic.Add(q, nums[q]);
}
Array.Sort(nums);
int i = 0, j = nums.Count() - 1;
int[] resArr = new int[2];
while (i < j)
{
if (nums[i] + nums[j] == target)
{
//已知value,求key
if (nums[i] != nums[j])
{
resArr[0] = srcDic. Where(r => r.Value == nums[i]). Select(r => r.Key).First();
resArr[1] = srcDic.Where(r => r.Value == nums[j]).Select(r => r.Key).First();
}
if (nums[i] == nums[j])
{
resArr[0] = srcDic.Where(r => r.Value == nums[i]).Select(r => r.Key).ToList()[0];
resArr[1] = srcDic.Where(r => r.Value == nums[i]).Select(r => r.Key).ToList()[1];
}
return resArr;
}
else if (nums[i] + nums[j] > target)
j--;
else
i++;
}
return resArr;
}