[英]Search in multidimensional array in C#
我有多維數組
int[,] PDATVL = new int[100,2];
設偽數據為:
249 398
249 423
249 448
249 473
249 498
251 17
251 42
251 325
252 142
252 418
253 194
254 7
254 319
255 81
255 378
現在,我想在數組中搜索251、142對。 除了線性搜索,什么是最好的方法?
如果您正在使用配對,為什么不使用結構
HashSet<KeyValuePair<int, int>>
要么
List<KeyValuePair<int, int>>
如果不在.NET 4。
然后,您可以搜索這樣的一對:
pairs.Where(p=> p.Key == 251 && p.Value == 142);
給定數組以詞法順序排序,您有兩個選擇:
IComparable<T>
和IEquatable<T>
我會選擇第二種。 這種結構的基本實現是:
public struct Pair : IComparable<Pair>, IEquatable<Pair>
{
private readonly int x;
private readonly int y;
public Pair(int x, int y)
{
this.x = x;
this.y = y;
}
public int X { get { return x; } }
public int Y { get { return y; } }
public int CompareTo(Pair other)
{
return (x == other.x) ? y.CompareTo(other.y) : x.CompareTo(other.x);
}
public bool Equals(Pair other)
{
return x == other.x && y == other.y;
}
}
現在,您可以使用Array.BinarySearch
方法:
var pairs = new[] {new Pair(1, 1), new Pair(1,2), new Pair(1, 3), new Pair(2, 3), new Pair(2, 4)};
// Returns 2
int index1 = Array.BinarySearch(pairs, new Pair(1,3));
// No match. Returns a negative number.
int index2 = Array.BinarySearch(pairs, new Pair(1, 4));
如果數組已排序,則可以使用二進制搜索。
內置方法Array.BinarySearch
僅處理一維數組,因此您必須自己實現。
如果該對中每個值都有一個最大值,則可以將它們組合為一個值,如下所示:
long pair = value1 * 10000000 + value2; // assuming value2 < 1000000
然后將它們存儲在Dictionary(或.NET 4中的HashSet)中,以便搜索為O(1):
var d = new Dictionary<long, object>;
long pair1 = 251 * 1000000 + 142;
d.Add(pair1, null);
long pair 2 = ....
// ...
var exists = d.ContainsKey(pair1);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.