방법 C 번호를 사용 int 배열의 가장 일반적인 값을 얻기 위해Int 배열에서 가장 일반적인 값을 얻는 방법은 무엇입니까? (C 번호)
는예 : 배열이 다음 값 갖는다 : 1, 1, 1,
Ans By의 2이어야 1
방법 C 번호를 사용 int 배열의 가장 일반적인 값을 얻기 위해Int 배열에서 가장 일반적인 값을 얻는 방법은 무엇입니까? (C 번호)
는예 : 배열이 다음 값 갖는다 : 1, 1, 1,
Ans By의 2이어야 1
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();
일부 구식 효율적인 루핑 :
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 팔꿈치 기름을 파열시키고 그것을 끝내는 데는 아무런 문제가 없습니다. –
두 번째 부분은'MaxBy()'를 사용하여 단순화 할 수 있습니다. LINQ에는 실제로 없지만 [MoreLinq] (http://code.google.com/p/morelinq/wiki/OperatorsOverview)에 있습니다. – svick
아마 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
처음에는 배열을 정렬하지 않았습니다. :) 어쨌든 정렬을하면 더 간단하게 처리 할 수 있습니다. 하나의 for 루프와 몇 개의 변수 만 있으면 충분합니다. – IVlad
@IVlad : 코드 첫 줄이 아니 었나요? 어쨌든, 네 말이 맞아. –
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;
}
나는이 게시물은 오래 알고 있지만, 누군가가 오늘 나에게이 질문의 역을 물었다. 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;
는 정수 값의 도메인에 대한 제한이 있습니까? IE. 모두 0과 10 사이의 값입니까? –
@Michael Petito : 네. 범위가 너무 크지 않으면 정말 빨리 처리 할 수 있습니다. –
int가 모두 0보다 크거나 같지 않습니다. – mouthpiec