日期:2014-05-20 浏览次数:20824 次
using System; using System.Collections.Generic; using System.Text; using System.Collections; namespace 算法大挑战 { class Program { public ArrayList arr = new ArrayList(); private int MajorityElement(int[] array,int n) { int count = 0; int num = 0; for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { if ((array[i]^array[j])==0) { count++; if ((double)(count / 8) > 0.5) { num = array[i]; } } } } return num; } static void Main(string[] args) { int[] array ={2,2,3,4,2,5,3,2,2,2}; int n = array.Length; Program p = new Program(); int num = p.MajorityElement(array,n); Console.WriteLine("{0}",num); Console.ReadKey(); } } }
------解决方案--------------------
如过数组是有序的,我的思路如下:
int MajorityElement(int array[],int n) { int NoMajorityElement=-1; int len=array[].length; int n=array[0]; int num=0; for(int i=1;i<len;i++) { if(array[i]=n) { num++; float fl=num/len; if(fl>= o.51) { retrun n; break; } } else { n=array[i]; num=0; } if(i=m) { return NoMajorityElement; } }
------解决方案--------------------
让我走走诡异路线:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; namespace ConsoleApplication2 { class Program { static int MajorityElement(int[] array, int n) { string s = ""; Array.Sort(array); for (int i = 0; i < array.Length; i++) s += array[i]; int iTemp = 0; int iMax = 0; MatchCollection mc = Regex.Matches(s, @"(\d)\1+"); foreach (Match m in mc) { iTemp = m.Value.Length; if (iMax < iTemp) { iMax = iTemp; n = Convert.ToInt32(m.Value[0].ToString()); } } if (iMax > array.Length / 2) return n; return -1; } static void Main(string[] args) { int[] array = { 2, 2, 3, 4, 2, 5, 3, 2, 2, 2 }; int n = array.Length; int num = MajorityElement(array, n); Console.WriteLine("{0}", num); Console.ReadKey(); } } }
------解决方案--------------------
public find(int[] arr){ //只有当某一元素在数组中的绝对数超过50%,函数才能返回最多数。 int ele=0;
int rud=0;
foreach(int n in arr)
{
if(rud==0)
{
ele=n;
rud=1;
}
else if(ele==n)
{
rud++;
}
else
{
rud--;
}
}
if(rud>0) return ele
return 0;
}
------解决方案--------------------