gpt4 book ai didi

c - 数组中出现次数最少的数

转载 作者:行者123 更新时间:2023-11-30 19:16:53 25 4
gpt4 key购买 nike

我在使用此功能时遇到问题。我已经测试过这个输入

Input : 2 2 3 4 4

Output : 3

目前为止一切正常。但是当我有两个或更多处于这种特殊情况的号码时:

Input : 1 3 3 4

Output : 4

我不断得到索引最大的数字。我真正想要的是这种情况下的输出(具有最小索引的数字):

Output : 1

这是我的代码:

int leastFreq (int v[] , int size)
{
int i ;
int count = 0;
int repetitions = 0;
int lower;

for ( i = 0 ; i < size ; i ++)
{
if (v[i] != v[i+1])
{
count --;
if ( count < repetitions)
{
repetitions = count;
lower = v[i];
}
}
else
{ count = 0 ;}
}
return lower;
}

如何解决此问题?(这是一个排序数组)

最佳答案

在此代码中,minnum 将包含最小频率数。a[0..size-1]

#include<stdio.h>
int main()
{
int n;
scanf("%d",&n);
int a[n];
for(int i=0;i<n;i++)
scanf("%d",&a[i]);
int min=65536;
int minnum=a[0];

int i,ct=1;
for(i=1;i<=n-1;i++)
{
if(a[i]==a[i-1])
{
ct++;
}
else
{
if(ct<min)
{
min=ct;
ct=1;
minnum=a[i-1];
}
}
}
if(ct<min)
{
min=ct;
ct=1;
minnum=a[i-1];
}
printf("%d",minnum);
}

The algorithm is First set a variable that implies occurence of a number to maximum possible number.

Then go on checking the equal numbers. When unequality occurs b/w 2 consecutive numbers just check if the number's occurence is less than the prev number's occurence.

Out side the loop it is also checked as it is required when the numbers end in a series of equal number like 1,1,1,2,2

关于c - 数组中出现次数最少的数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29193699/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com