你必须使用基于哈希表的关联数组(也称为字典)。查找的平均时间复杂度为O(1 + n/k),最坏情况下为O(n)。你必须将表组织成列的字典(以列名作为键),而列必须是值的字典(以行名作为键)。
更多信息:
http://en.wikipedia.org/wiki/Dictionary_(data_structure)
http://en.wikipedia.org/wiki/Hash_table
C#示例:
using System;
using System.Collections;
using System.Collections.Generic;
namespace Test {
public class Test
{
class Table {
class Column {
public Dictionary<string, string> cells;
public Column() {
cells = new Dictionary<string, string>();
}
public string Find(string rowName) {
string resultValue;
if (cells.TryGetValue(rowName, out resultValue))
return resultValue;
else
throw new Exception("oops, no such cell");
}
}
Dictionary<string, Column> columns;
List<string> rowNames;
public Table() {
columns = new Dictionary<string, Column>();
rowNames = new List<string>();
}
public void AddColumn(string columnName, params string[] values) {
Column column = new Column();
columns.Add(columnName, column);
int counter = 0;
foreach (string rowName in rowNames) {
if (counter < values.Length)
column.cells.Add(rowName, values[counter]);
else
column.cells.Add(rowName, "");
counter++;
}
}
public void AddRow(string rowName, params string[] values) {
rowNames.Add(rowName);
int counter = 0;
foreach (KeyValuePair<string, Column> columnPair in columns) {
Column column = columnPair.Value;
if (counter < values.Length)
column.cells.Add(rowName, values[counter]);
else
column.cells.Add(rowName, "");
counter++;
}
}
public string Find(string columnName, string rowName) {
Column resultColumn;
if (columns.TryGetValue(columnName, out resultColumn))
return resultColumn.Find(rowName);
else
throw new Exception("oops, no such cell");
}
}
public static void Main()
{
Table table = new Table();
table.AddRow("a");
table.AddRow("b");
table.AddColumn("column 1", "asd", "asgf");
table.AddColumn("column 2", "awd", "aasf");
table.AddColumn("column 3", "asfc", "asgfc");
Console.WriteLine(table.Find("column 1", "b") );
}
}
}