LEETCODE 第一题 两数之和用C#实现
暴力求解法 时间复杂度为O(N2):
public class Solution {
public int[] TwoSum(int[] nums, int target) {
int[] res =new int[2];
for(int i=0;i<nums.Length;i++) //注意nums的最后一位,多加了个等于号,编译错误
{
for(int j=i+1;j<nums.Length;j++)
{
if(nums[i]+nums[j]==target)
{
res[0]=i;
res[1]=j;
return res; //终止循环条件
}
}
}
return res; //返回值
}
}
哈希表:
c#哈希表用法:
声明
Hashtable ht = new Hashtable();
查重
ht.Contains(key)
添加
ht.Add(key,value);
修改
ht[key] = value;
移除
ht.Remove(key);
清空
ht.Clear();
遍历哈希表
foreach(DictionaryEntry c in ht1)
{
Console.Write(c.Key+" “+c.Value+”\n");
}
【注】遍历哈希表时,foreach的变量类型不可以用var,只能用DictionaryEntry,这与字典不同
//判断两个哈希表内元素是否相等
bool isSame=ht1.Cast<DictionaryEntry>()
.Union(ht2.Cast<DictionaryEntry>())
.Count()
== ht1.Count
&& ht1.Count==ht2.Count;
//利用哈希表统计频次
Hashtable ElementCount(int[] array)
{
Hashtable ht= new Hashtable();
foreach(var i in array)
{
if(ht.Contains(i))
ht[i]=(int)ht[i]+1;
else
ht.Add(i,1);
}
return ht;
}
一边查找,一边存进dic,在dic里查找目标值-当前值的差值,要注意Key值重复问题,这里使用重复的key值不储存的办法。
public int[] TwoSum(int[] nums, int target) {
Dictionary<int, int> dic =new Dictionary<int, int>();
int[] res=new int[2];
for(int i=0;i<nums.Length;i++)
{
int cha = target-nums[i];
if(dic.ContainsKey(cha))
{
res[0]=dic[cha];
res[1] = i;
return res;
}
else
{
if ( !dic.ContainsKey(nums[i]))//重复的key不存进dic
{
dic.Add(nums[i], i);
}
}
}
return res;
}
文章详细介绍了如何使用C#编程语言解决LEETCODE的第一题——两数之和。首先展示了暴力求解法的时间复杂度为O(N^2),然后引入哈希表以提高效率,避免了重复检查,降低了时间复杂度。同时,文章提供了哈希表的C#操作方法,包括添加、修改、查重等,并给出了利用哈希表解决此问题的具体代码实现。
753

被折叠的 条评论
为什么被折叠?



