1. Two Sum
Posted HenRy
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了1. Two Sum相关的知识,希望对你有一定的参考价值。
Difficulty: Easy
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].UPDATE (2016/2/13):
The return format had been changed to zero-based indices. Please read the above updated description carefully.
假设一定存在数组其中的2个数相加等于目标值,那么只需要循环数组,2个for循环嵌套一个个的相加得到和数等于目标值返回即可,于是就是第一种方法。复杂度O(n2),空间复杂度O(1).
My submission 1: Accepted Runtime: 648ms
1 public int[] TwoSum(int[] nums, int target) { 2 int[] result=new int[2]; 3 for (int i = 0; i<nums.Length; i++) 4 { 5 for (int j = i + 1; j < nums.Length; j++) 6 { 7 if (nums[i] + nums[j] == target) 8 { 9 result[0] = i; 10 result[1] = j; 11 return result; 12 } 13 } 14 } 15 return result; 16 }
考虑到第一个方法的O(n2)的复杂度,我们需要改良,循环存数进字典,倘若里面有值等于目标值-现在的值那么即匹配,返回2个坐标值。时间复杂度O(n),空间复杂度O(n)。
My submission 2: Accepted Runtime: 476ms
1 public int[] TwoSum(int[] nums, int target) { 2 Dictionary<int, int> dic=new Dictionary<int, int>(); 3 for (int i = 0; i < nums.Length; i++) 4 { 5 if(dic.ContainsKey(target-nums[i])) 6 return new int[] {dic[target-nums[i]],i}; 7 else if(!dic.ContainsKey(nums[i])) 8 { 9 dic.Add(nums[i],i); 10 } 11 } 12 return new int[] {0,0}; 13 }
以上是关于1. Two Sum的主要内容,如果未能解决你的问题,请参考以下文章