2010-04-16 8 views
13

방법 C 번호를 사용 int 배열의 가장 일반적인 값을 얻기 위해Int 배열에서 가장 일반적인 값을 얻는 방법은 무엇입니까? (C 번호)

예 : 배열이 다음 값 갖는다 : 1, 1, 1,

Ans By의 2이어야 1

+0

는 정수 값의 도메인에 대한 제한이 있습니까? IE. 모두 0과 10 사이의 값입니까? –

+0

@Michael Petito : 네. 범위가 너무 크지 않으면 정말 빨리 처리 할 수 ​​있습니다. –

+0

int가 모두 0보다 크거나 같지 않습니다. – mouthpiec

답변

26
var query = (from item in array 
     group item by item into g 
     orderby g.Count() descending 
     select new { Item = g.Key, Count = g.Count() }).First(); 

단지 값이 아닌 카운트를 들어, 두 번째에

var query = (from item in array 
       group item by item into g 
       orderby g.Count() descending 
       select g.Key).First(); 

람다 버전을 수행 할 수 있습니다

var query = array.GroupBy(item => item).OrderByDescending(g => g.Count()).Select(g => g.Key).First(); 
+0

+1, 내 마음보다 빠르고 좋아. –

+0

O (nlogn) 정렬 작업을 수행하지 않습니까? – liori

+1

@liori : 예. 정렬은 가장 높은 계산을 찾는 가장 효율적인 방법은 아닙니다. – Guffa

14

일부 구식 효율적인 루핑 :

var cnt = new Dictionary<int, int>(); 
foreach (int value in theArray) { 
    if (cnt.ContainsKey(value)) { 
     cnt[value]++; 
    } else { 
     cnt.Add(value, 1); 
    } 
} 
int mostCommonValue = 0; 
int highestCount = 0; 
foreach (KeyValuePair<int, int> pair in cnt) { 
    if (pair.Value > highestCount) { 
     mostCommonValue = pair.Key; 
     highestCount = pair.Value; 
    } 
} 

이제 mostCommonValue 가장 일반적인 값을 포함하고 highestCount는 발생 횟수가 포함되어 있습니다.

+1

+1 팔꿈치 기름을 파열시키고 그것을 끝내는 데는 아무런 문제가 없습니다. –

+0

두 번째 부분은'MaxBy()'를 사용하여 단순화 할 수 있습니다. LINQ에는 실제로 없지만 [MoreLinq] (http://code.google.com/p/morelinq/wiki/OperatorsOverview)에 있습니다. – svick

1

아마 O (N 로그 n),하지만 빠른 :

sort the array a[n] 

// assuming n > 0 
int iBest = -1; // index of first number in most popular subset 
int nBest = -1; // popularity of most popular number 
// for each subset of numbers 
for(int i = 0; i < n;){ 
    int ii = i; // ii = index of first number in subset 
    int nn = 0; // nn = count of numbers in subset 
    // for each number in subset, count it 
    for (; i < n && a[i]==a[ii]; i++, nn++){} 
    // if the subset has more numbers than the best so far 
    // remember it as the new best 
    if (nBest < nn){nBest = nn; iBest = ii;} 
} 

// print the most popular value and how popular it is 
print a[iBest], nBest 
+0

처음에는 배열을 정렬하지 않았습니다. :) 어쨌든 정렬을하면 더 간단하게 처리 할 수 ​​있습니다. 하나의 for 루프와 몇 개의 변수 만 있으면 충분합니다. – IVlad

+0

@IVlad : 코드 첫 줄이 아니 었나요? 어쨌든, 네 말이 맞아. –

1
public static int get_occure(int[] a) 
    { 
     int[] arr = a; 
     int c = 1, maxcount = 1, maxvalue = 0; 
     int result = 0; 
     for (int i = 0; i < arr.Length; i++) 
     { 
      maxvalue = arr[i]; 
      for (int j = 0; j <arr.Length; j++) 
      { 

       if (maxvalue == arr[j] && j != i) 
       { 
        c++; 
        if (c > maxcount) 
        { 
         maxcount = c; 
         result = arr[i]; 

        } 
       } 
       else 
       { 
        c=1; 

       } 

      } 


     } 
     return result; 
    } 
1

나는이 게시물은 오래 알고 있지만, 누군가가 오늘 나에게이 질문의 역을 물었다. Guffa의 유사

LINQ 그룹화

sourceArray.GroupBy(value => value).OrderByDescending(group => group.Count()).First().First(); 

온도 컬렉션 :

var counts = new Dictionary<int, int>(); 
foreach (var i in sourceArray) 
{ 
    if (!counts.ContainsKey(i)) { counts.Add(i, 0); } 
    counts[i]++; 
} 
return counts.OrderByDescending(kv => kv.Value).First().Key; 
관련 문제