twoSum
2018-02-11 16:29
246 查看
given an array of Integers ,find two numbers such that they add up to a specific target number.
The function twoNum should return indices of the two numbers such that they add up to the targer, where index1 must be less than index2 Please note that your returned answers (both index1 and index2) are not zero-based.
code example 1:
/// <summary>
/// given an array of integers, find two numbers such that they add up to a specific target number
/// the function TwoSum should return indices of the two numbers such that they add up to the target ,where index1 must be less than index2, Please note that your returned answers (both index1 and index2 ) are non-zero-based.
/// You may assume that each input would have exactly one solution.
/// </summary>
/// <param name="num"></param>
/// <param name="targetnum"></param>
/// <returns></returns>
static int[] Method_5(int[] num,int targetnum)
{
Dictionary<int, int> dictionary = new Dictionary<int, int>();
for(int i = 0; i < num.Length; i++)
{
dictionary.Add(num[i], i);
}
for(var i=0;i<num.Length;i++)
{
if (dictionary.Keys.Contains(targetnum - i))
{
int v = dictionary[targetnum - i];
if (v != null && v > i)
{
return new int[] { i + 1, v + 1 };
}
}
}
return null;
}
The function twoNum should return indices of the two numbers such that they add up to the targer, where index1 must be less than index2 Please note that your returned answers (both index1 and index2) are not zero-based.
code example 1:
/// <summary>
/// given an array of integers, find two numbers such that they add up to a specific target number
/// the function TwoSum should return indices of the two numbers such that they add up to the target ,where index1 must be less than index2, Please note that your returned answers (both index1 and index2 ) are non-zero-based.
/// You may assume that each input would have exactly one solution.
/// </summary>
/// <param name="num"></param>
/// <param name="targetnum"></param>
/// <returns></returns>
static int[] Method_5(int[] num,int targetnum)
{
Dictionary<int, int> dictionary = new Dictionary<int, int>();
for(int i = 0; i < num.Length; i++)
{
dictionary.Add(num[i], i);
}
for(var i=0;i<num.Length;i++)
{
if (dictionary.Keys.Contains(targetnum - i))
{
int v = dictionary[targetnum - i];
if (v != null && v > i)
{
return new int[] { i + 1, v + 1 };
}
}
}
return null;
}
相关文章推荐
- LeetCode1: TwoSum
- LeetCode题解—TwoSum
- LeetCode-TwoSum
- 1_TwoSum
- {Leetcode} 1。TwoSum
- JSer的leetcode征途--TwoSum
- LeetCode(1) - twoSum
- 1 twoSum
- LeetCode--1.TwoSum
- LeetCode之路——LeetCode_1_TwoSum
- twoSum
- twoSum
- LeetCode刷题之第一题——TwoSum
- 1 TwoSum
- [LeetCode Problem]TwoSum
- 面试:数组:twosum
- LeetCode 第1题 TwoSum
- #1 TwoSum_leetcode
- LeetCode(1)--TwoSum
- LeetCode--1.TwoSum