最近从一篇博文里看到一个面试题,找出第一个只出现一次的数,觉得挺有意思的,于是拿过来学习一下,这篇博文出处是《面试题35:第一个只出现一次的数》。这里原文是用python写的,因为目前为止,本人对python还不是很熟悉,借此学习吧。我用C#把这个功能也实现出来。另外又想到一个扩展,就是如果把这个序列中只出现一次的数都找出来呢?
1. python实现
# !/usr/bin/python
# FileName: FirstNotRepeatingChar.py
def FirstNotRepeatingChar(string):
hashStr = [0] * 256
for c in string:
hashStr[ord(c)] += 1
for c in string:
if hashStr[ord(c)] == 1:
return c
# Test
testStr=('3','4','3','4','2');
print(FirstNotRepeatingChar(testStr));
tStr='3255242424';
print(FirstNotRepeatingChar(tStr));
# 分别输出2 和 3
经过测试,使用元组或者数字组成的字符串都是可以的,真是很喜欢python的这种特点!
注:这里说下ord, 可以作为atoi来用,功能是若给定的参数是一个长度为1的字符串,那么若参数是Unicode对象,则返回对应的整数,若为8-bit的string,则返回对应的值。
2、C#实现上面的例子
static void Main(string[] args)
{
string[] readStr = {"e","e","a","a","c","d","a","c"};
Dictionary<string, int> countStr = new Dictionary<string, int>();
foreach (string str in readStr)
{
if (countStr.ContainsKey(str))
countStr[str]++;
else
countStr.Add(str, 1);
}
foreach (KeyValuePair<string, int> keyvalue in countStr)
{
if (keyvalue.Value == 1)
{
Console.WriteLine(keyvalue.Key + "," + keyvalue.Value);
break;
}
}
}
很明显,在C#里实现的并不如在python里方便,主要在数据类型和集合的使用上。输出出现一次的循环里,必须要使用break;否则把次数有一次的全部输出了。不知道有更好的解决办法吗?在这里使用的是Dictionary,如果在C#里使用Hash应该也是可以的吧?待补充。
3、扩充:统计这个集合内的元素频次
如果我们要把这个集合内的元素都统计一下,就是把元素和频次都输出。就是把上面的例子稍改动一下就可以。
static void Main(string[] args)
{
string[] readStr = {"e","e","a","a","c","d","a","c"};
Dictionary<string, int> countStr = new Dictionary<string, int>();
foreach (string str in readStr)
{
if (countStr.ContainsKey(str))
countStr[str]++;
else
countStr.Add(str, 1);
}
foreach (KeyValuePair<string, int> keyvalue in countStr)
{
Console.WriteLine(keyvalue.Key + "," + keyvalue.Value);
}
}
我们还想要按频次从大到小排个序,加一个顺序的linq查询语句。
static void Main(string[] args)
{
string[] readStr = {"e","e","a","a","c","d","a","c"};
Dictionary<string, int> countStr = new Dictionary<string, int>();
foreach (string str in readStr)
{
if (countStr.ContainsKey(str))
countStr[str]++;
else
countStr.Add(str, 1);
}
var list = countStr.OrderByDescending(s => s.Value);
foreach (KeyValuePair<string, int> keyvalue in list)
{
Console.WriteLine(keyvalue.Key + "," + keyvalue.Value);
}
}
4、用Python实现统计频次
mylist = [2,2,2,2,2,2,3,3,3,3]
myset = set(mylist)
for item in myset:
print(item,mylist.count(item))
如此简单!!