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.git
Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].
难度:低
分析:要求给定的数组,查找其中2个元素,知足这2个元素的相加等于给定目标target的值。
思路:通常的思路,咱们遍历数组元素,假设当前遍历的数组元素x,再次遍历x以后的数组元素,假设当前再次遍历的数组元素y,判断x+y是否知足target,若是知足,则返回x,y下标,不然继续遍历,直至循环结束。考虑这种算法的时间复杂度是O (n²),不是最优的解法。
跟前面几章相似,咱们能够考虑用哈希表来存储数据,这里用C#提供的Hashtable来存储下标-对应值(key-value)键值对;
接着遍历数组元素,若是目标值-当前元素值存在当前的Hashtable中,则代表找到了知足条件的2个元素,返回对应的下标;
若是Hashtable没有知足的目标值-当前元素值的元素,将当前元素添加到Hashtable,进入下一轮遍历,直到知足上一条的条件。github
public int[] TwoSum(int[] nums, int target) { var map = new Hashtable(); ; for (int i = 0; i < nums.Length; i++) { int complement = target - nums[i]; //匹配成功,返回结果 if (map.ContainsKey(complement)) { return new int[] { (int)map[complement], i }; } map.Add(nums[i], i); } return null; }