2

这从我之前的问题继续。

我有一个数组,想在其中找到最大的数字。但是我不能排序,因为数字的索引非常重要,所以不能移动。最后,我的问题的输出应该是“最大的数字在索引 1 和 4 中,数字为 8。这是数组:

int anonarray[5] = {3,8,7,5,8};
4

3 回答 3

3
enum { MAX_ENTRIES = 5 };
int anonarray[MAX_ENTRIES] = { 3, 8, 7, 5, 8 };
int maxval = anonarray[0];
int maxidx[MAX_ENTRIES] = { 0, 0, 0, 0, 0 };
int maxnum = 1;

for (int i = 1; i < MAX_ENTRIES; i++)
{
    if (maxval < anonarray[i])
    {
        /* New largest value - one entry in list */
        maxval = anonarray[i];
        maxnum = 1;
        maxidx[0] = i;
    }
    else if (maxval == anonarray[i])
    {
        /* Another occurrence of current largest value - add entry to list */
        maxidx[maxnum++] = i;
    }
}

printf("The biggest number is in %s", ((maxnum > 1) ? "indices" : "index"));
const char *pad = " ";
for (int i = 0; i < maxnum - 1; i++)
{
    printf("%s%d", pad, maxidx[i]);
    pad = ", ";
}
printf(" %s%d, with value %d.\n", ((maxnum > 1) ? "and " : ""),
       maxidx[maxnum-1], maxval);

请注意,将特定于英语的格式国际化并不一定容易!

于 2012-10-09T00:15:19.803 回答
2

循环遍历数组以找到最大值:

int max = a[0], count = 0;

for(i=1;i<n;i++)
  if(max<a[i]) 
     max=a[i]; 

for(i=0;i<n;i++)
  if(max==a[i]) 
     count++; //num of maximums

现在声明一个数组来存储索引:

int index[count], j=0;

for(i=0;i<n;i++)
{
 if(a[i]==max)
   index[j++]=i;
}

现在index有具有元素的索引列表max

这是渐近的 O(n) 并且可能是最少的内存。

于 2012-10-09T00:20:52.023 回答
0

这可以通过使用对指针数组进行排序的技术来解决。就像是:

int a[5] = {3,8,7,5,8};
int *pa[5];
for (int i = 0; i < 5; i++) {
    pa[i] = &a[i];
}
sort(pa); // pseudocode, be sure to sort by what pa[i] points to
for (int i = 0; i < 5; i++) {
    printf("n=%d index=%d\n", *pa[i], pa[i] - a);
}
于 2012-10-09T00:13:11.120 回答