我试图找到数组中最不频繁的元素,我尝试使用插入排序对数组进行排序,然后使用两个循环;用于拾取每个元素和内部循环的外部循环以进行比较。
# include <stdio.h>
void LeastFrequentnum(int arr[],int n);
void InsertionSort(int arr[],int n);
int main()
{
int arr[] = {1, 3, 2, 1, 2, 2, 3, 1};
int n = sizeof(arr)/sizeof(arr[0]);
LeastFrequentnum(arr,n);
}
void LeastFrequentnum(int arr[],int n)
{
InsertionSort(arr,n);
int count = 1;
int min_count = n+1;// i will update min_count
int res=-1; // used to store the element which occurs least number of times
for(int i=0;i<n;)
{
count=1;
for(int j=i+1;j<n;j++)
{
if(arr[j]==arr[i])
{
count++;
}
else
{
i = j+1;
if(count<min_count)
{
min_count = count;
res = arr[j];
break;
}
}
}
}
printf("%d",res);
}
void InsertionSort(int arr[],int n)
{
for(int i=1;i<n;i++)
{
int key = arr[i];
int j = i-1;
while(j>=0 && arr[j]>key)
{
arr[j+1] = arr[j];
j--;
}
arr[j+1]=key;
}
}
我尝试运行它,但运行时结果是超出时间限制的问题。
我认为这部分代码 - > for(int i=0;i<n;)
我想你错过了i ++
好像有无穷无尽的循环。试试这个。
# include <stdio.h>
void LeastFrequentnum(int arr[],int n);
void InsertionSort(int arr[],int n);
int main()
{
int arr[] = {1, 3, 2, 1, 2, 2, 3, 1};
int n = sizeof(arr)/sizeof(arr[0]);
LeastFrequentnum(arr,n);
}
void LeastFrequentnum(int arr[],int n)
{
InsertionSort(arr,n);
int count = 1;
int min_count = n+1;// i will update min_count
int res=-1; // used to store the element which occurs least number of times
for(int i=0;i<n;i++)
{
count=1;
for(int j=i+1;j<n;j++)
{
if(arr[j]==arr[i])
{
count++;
}
else
{
i = j+1;
if(count<min_count)
{
min_count = count;
res = arr[j];
break;
}
}
}
}
printf("%d",res);
}
void InsertionSort(int arr[],int n)
{
for(int i=1;i<n;i++)
{
int key = arr[i];
int j = i-1;
while(j>=0 && arr[j]>key)
{
arr[j+1] = arr[j];
j--;
}
arr[j+1]=key;
}
}