
问题
给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。
你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用。
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
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.
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
示例
public class Program { public static void Main(string[] args) { int[] nums = { 2, 7, 11, 15 }; var res = TwoSum(nums, 9); var res2 = TwoSum2(nums, 9); Console.WriteLine($"[{res[0]},{res[1]}]"); Console.WriteLine($"[{res2[0]},{res2[1]}]"); Console.ReadKey(); } public static int[] TwoSum(int[] nums, int target) { //类似于冒泡,双循环比较2个数的和与目标值是否相等 for (int i = 0; i < nums.Length; i++) { for (int j = i + 1; j < nums.Length; j++) { if (nums[i] + nums[j] == target) { return new int[] { i, j }; } } } //找不到时抛出异常 throw new ArgumentException(); } public static int[] TwoSum2(int[] nums, int target) { //用数组中的值做key,索引做value存下所有值 var dictionary = new Dictionary<int, int>(); for (int i = 0; i < nums.Length; i++) { //记录差值 int complement = target - nums[i]; //若字典中已经存在这个值,说明匹配成功 if (dictionary.ContainsKey(complement)) { return new int[] { dictionary[complement], i }; } //记录索引 dictionary[nums[i]] = i; } //找不到时抛出异常 throw new ArgumentException(); } }
以上给出2种算法实现,以下是这个案例的输出结果:
[0,1] [0,1]
分析:
显而易见,TwoSum 的时间复杂度为: ,TwoSum2 的时间复杂度为:
。
本文由 .Net中文网 原创发布,欢迎大家踊跃转载。
转载请注明本文地址:https://www.byteflying.com/archives/3762。