e...你的问题是两个问题...1. C#下高效遍历数组
2. 查找重复值对于第一个, 如果确实性能要求高的, 直接用指针..
int[] arr=new int[]{...};
int* p=&arr[0];
然后用p[index]存取值.
对于第二个 ,经典方法是在stack上开一个辅助大数组int* asstArr=stackalloc int[256];, 用原数组的值作为辅助数组的下标.
遍历原数组,asstArr[p[index]]++; 最后这个值就是p[index]出现的次数.
2. 查找重复值对于第一个, 如果确实性能要求高的, 直接用指针..
int[] arr=new int[]{...};
int* p=&arr[0];
然后用p[index]存取值.
对于第二个 ,经典方法是在stack上开一个辅助大数组int* asstArr=stackalloc int[256];, 用原数组的值作为辅助数组的下标.
遍历原数组,asstArr[p[index]]++; 最后这个值就是p[index]出现的次数.
具体操作 搜下 sql保留一条重复数据 就可以了
Hashtable ht = new Hashtable();I assume a simple an array.// Declare and set array element values
int[] array2 = new int[] { 1, 3,5,5, 5, 7,7,9,9,9,9,9,9, 9 };I need to iterate through the collection array2 to count the times of each element which appears in the collection.
So the computing time is O(n).
when I increase the value,it is easy to find if there is a key that has existed in the Hashtable now.Then I can get the final ht.
ht[1] = 1
ht[3] = 1
ht[5] = 2
ht[7] = 2
ht[9] = 7After we build the final ht,we can search the content and its repeated times very easily.
{
int[] arr = new int[]{...};
int* p = &arr[0];
}仅供参考...
usafe
{
int[] arr = new int[]{...};
int* p = &arr[0];
}
然后(右键)项目.属性->生成, 把"允许不安全代码"勾上后重新编译就可...
那么你用数组中最大的一个数来实例化一个新的int数组
int[] result = new [20];
并初始化result所有元素都为0然后遍历一次data
foreach(int i in data)
{
result[i] += 1;
}之后,比如你想知道5这个数是否在数组data里存在,那么只要判断result[5]是否大于0,那么result[5]的值就是5在数组data里重复出现的次数.上面是大概算法的描述至于要执行速度最快,那么就是用point,以及在Stack上(而不是heap上)开空间操作,那就需要使用unsafe代码,或者你用c++写代码.
如果是asp.net程序中
建议使用托管代码
对于非stackalloc的, 用指针首先固定长度初始化应该是Int32[] arr = {1,2,3}; 并且不可以直接取地址操作.Int32 *ip = &arr[0]; 需要fixed吧..如果只是单个的Int32变量写成Int32 *ip = &某个变量是没问题的.如果是从数据库取出来的..尽量通过T-SQL解决吧..
如果是已经存在的非数据库媒体存储的...我觉的还是用散列..用Dictionary<string, uint>
Contains的时候..后面++值 ..在使用Dictionary时最后先初始化它的capacity..为你的数组的length * 2..因为它的实现应该是平方探测.
{
public SolidPoint()
{
//
// TODO: 在此处添加构造函数逻辑
//
} private byte _height = 1; /// <summary>
/// 高度,放电个数
/// </summary>
public byte height
{
get
{
return this._height;
}
set
{
this._height = value;
}
} private Point _Coordinate; /// <summary>
/// 坐标点
/// </summary>
public Point Coordinate
{
get
{
return this._Coordinate;
}
set
{
this._Coordinate = new Point(value.X,value.Y);
} }
}List<SolidPoint> ls = new List<SolidPoint>();
for (int i = 0; i < ls.Count - 1;i++ )
{
for (int j = i + 1; j < ls.Count; j++)
{
if (ls[i].Coordinate == ls[j].Coordinate)
{
ls[i].height += 1;
ls.RemoveAt(j);
}
}
}
指针虽然能快,也有限,而且还是不安全代码。
Hash表存在不同对象Hash值相同的可能性。
用数据内容做下标的,数组占内存太大了,说不定就报异常。要我说,如果数据是整数这样的小数据,优化也没什么效果,真想快,就应该从一开始就进行排序,例如使用SortedList。那样统计重复数量的时候直接报结果行了。如果数据是大数据,譬如长字符串或者是Datatable的一个Row,就有了优化算法的必要了。可以把单个大数据分成几部分分层比较,每层比较都筛掉大多数的候选数据。越往后,比较次数越少,省略了很多不必要的比较。
实现:c# Hashtable,或者unsafe c++自己写一个Hash List。