private class ClsValueCount
{
private int m_Value;
private int m_Count;
public ClsValueCount(int p_intValue, int p_intCount)
{
m_Value = p_intValue;
m_Count = p_intCount;
}
public int Value
{
get
{
return m_Value;
}
set
{
m_Value = value;
}
}
public int Count
{
get
{
return m_Count;
}
set
{
m_Count = value;
}
}
}
private ClsValueCount GetValueCount(int p_intValue, ArrayList p_arrayList)
{
if (p_arrayList == null)
{
return null;
}
foreach (ClsValueCount valueCount in p_arrayList)
{
if (valueCount.Value == p_intValue)
{
return valueCount;
}
}
return null;
}
private ClsValueCount GetMaxValueCount(ArrayList p_arrayList)
{
if ((p_arrayList == null) || (p_arrayList.Count < 1))
{
return null;
}
if (p_arrayList.Count == 1)
{
return p_arrayList[0] as ClsValueCount;
}
ClsValueCount valueCountMax = null;
foreach (ClsValueCount valueCount in p_arrayList)
{
if ((valueCountMax == null) || (valueCountMax.Value < valueCount.Value))
{
valueCountMax = valueCount;
}
}
return valueCountMax;
}
private void ShowData(ArrayList p_arrayListValueCounts, RichTextBox p_richTextBox)
{
p_richTextBox.Text = "";
foreach (ClsValueCount valueCount in p_arrayListValueCounts)
{
p_richTextBox.Text += valueCount.Value.ToString() + " : " + valueCount.Count.ToString() + "\n";
}
}
private void button7_Click(object sender, System.EventArgs e)
{
Random random = new Random();
int[] arrInts = new int[100];
for (int i = 0; i < arrInts.Length; i++)
{
arrInts[i] = random.Next(100);
}
ArrayList arrayList = new ArrayList();
ClsValueCount valueCount = null;
for (int i = 0; i < arrInts.Length; i++)
{
valueCount = GetValueCount(arrInts[i], arrayList);
if (valueCount == null)
{
valueCount = new ClsValueCount(arrInts[i], 1);
arrayList.Add(valueCount);
}
else
{
valueCount.Count++;
}
}
ArrayList arrayListMax = new ArrayList();
foreach (ClsValueCount valueCount1 in arrayList)
{
if (arrayListMax.Count == 0)
{
arrayListMax.Add(valueCount1);
}
else
{
if (valueCount1.Count > ((ClsValueCount)arrayListMax[0]).Count)
{
arrayListMax.Clear();
arrayListMax.Add(valueCount1);
}
else if (valueCount1.Count == ((ClsValueCount)arrayListMax[0]).Count)
{
arrayListMax.Add(valueCount1);
}
}
}
ShowData(arrayList, richTextBox1);
ShowData(arrayListMax, richTextBox2);
valueCount = GetMaxValueCount(arrayListMax);
if (valueCount != null)
{
MessageBox.Show(valueCount.Value.ToString() + " " + valueCount.Count.ToString());
}
else
{
MessageBox.Show("MaxNotFound!");
}
}
算法保证正确, 不保证最优!
开始的时候我也考虑用Hashtable, 可是具体实现时有一些问题不好解决, 于是改成用自定义类ClsValueCount和ArrayList来实现.
ltr2002 ,有好算法的把代码贴出来, 大家一起学习.不要光说不练.
对于某些进行人身攻击的小人表示强烈抗议!!!
建议版主采取适当措施以维护本论坛交流学习的良好氛围
[此贴子已经被作者于2006-4-5 8:28:21编辑过]