Leetcode 1 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].
Solution:
经典的利用hashtable 存已经存在的值和找match的值的问题.Runtime is O(n)
public class Solution {
public int[] TwoSum(int[] nums, int target) {
Hashtable hashtable = new Hashtable();
if(nums.Count() == 0) return null;
int diff = 0;
int[] a = new int[2];
for(int i =0; i< nums.Count(); i++)
{
diff = target - nums[i];
if(hashtable.ContainsKey(nums[i]))
{
a[0] = (int)hashtable[nums[i]];
a[1] = i;
return a;
}
hashtable.Add(diff,i);
}
return null;
}
}