问题:
Design and implement a TwoSum class. It should support the following operations:add and find.
add - Add the number to an internal data structure.
find - Find if there exists any pair of numbers which sum is equal to the value.
For example,
add(1); add(3); add(5);
find(4) -> true
find(7) -> false
题意:设计和实施一个TwoSum类,它支持如下操作:增加和查找。
增加:增加成员到一个int类型的数据结构中。
查找:查找是否存在一对成员的和的值等于value。
例如:
add(1); add(3); add(5);
find(4)返回true;find(7)返回false
思路:直接照搬之前的TwoSum、TwoSum2的解法显然不行,因为要考虑到增加相同值的情况,所以要改动一下。仍然使用字典,key为number的值,value为number的个数。假如target-key==key,则判断key的value是否大于等于2,else,字典中是否有target-key的key。
代码如下:
class TwoSum
{
//由于后面测试了Add是否有问题,所以声明为public static
public static Dictionary<int, int> dictionary = new Dictionary<int, int>();
//获取所有的key,存储在集合中
Dictionary<int, int>.KeyCollection keyCollection = dictionary.Keys;
public void Add(int number)
{
if (dictionary.ContainsKey(number))
dictionary[number] += 1;
else
dictionary.Add(number, 1);
}
public bool Find(int target)
{
for(int j=0;j<dictionary.Count;j++)
{
int temp = target - keyCollection.ElementAt(j);
if (temp == keyCollection.ElementAt(j) && dictionary[j] >= 2)
return true;
else if (dictionary.ContainsKey(temp))
return true;
}
return false;
}
}
Main方法:
static void Main(string[] args)
{
TwoSum twoSum = new TwoSum();
twoSum.Add(1);
twoSum.Add(3);
twoSum.Add(1);
twoSum.Add(5);
//输出字典中的所有元素
foreach(KeyValuePair<int,int> i in TwoSum.dictionary)
{
Console.WriteLine("{0,-5}{1,-9}", i.Key, i.Value);
}
Console.WriteLine("Find(4):{0},Find(7):{1}", twoSum.Find(4), twoSum.Find(7));
Console.ReadKey();
}
总结:做这题查了字典的API好久,因为网上没有c#的代码
,所有的API都看了一两遍,思路还是比较清晰的,假如有其它解法的话欢迎和我交流。