有史以来活着的恐龙数量最多

largest number of dinosaurs that were ever alive

本文关键字:恐龙 活着 有史以来      更新时间:2023-10-16

可能的重复项:
算法解决一次找到最大没有

我们得到一个 2n 个整数的数组,其中这个整数数组中的每对分别代表恐龙的出生年份和死亡年份。我们要考虑的有效年份范围是 [-100000 到 2005]。例如,如果输入为:

-80000 -79950 20

70 22 60 58 65 1950 2004

这意味着第一只恐龙的出生年份分别为-80000和死亡年份-79950。同样,第二只恐龙的寿命从20岁到70岁,依此类推。

我们想知道有史以来活着的恐龙数量最多。编写一个方法来计算它,给定上面的 2n 个整数数组。

这是我到目前为止尝试过的:

#include<stdio.h>
#include<stdlib.h>
#include <stddef.h>
static void insertion_sort(int *a, const size_t n) 
{
    size_t i, j;
    int value;
    for (i = 1; i < n; i++) {
        value = a[i];
        for (j = i; j > 0 && value < a[j - 1]; j--) {
            a[j] = a[j - 1];
        }
        a[j] = value;
    }
}
int  main(){
    int arr[10]={-80000,-79950,20,70,22,60,58,65,1950,2004};
    int strt[5],end[5];
    int bal[5];
    int i,j,k,l,m,length;
    l=0;
    m=0;
    for (i=0; i<10; i++){
        //printf("i = %2d arr[i] = %2dn", i, arr[i]);
        if(i%2==0) {
            strt[l]=arr[i];
            l++;
        } else {
            end[m]=arr[i];
            m++;
        }
    }
    insertion_sort(strt, sizeof strt / sizeof strt[0]);
    insertion_sort(end, sizeof end / sizeof end[0]);
    k=sizeof(end)/sizeof(int);
    for(j=0;j<5;j++) {
        bal[i]=strt[i]-end[k-1];
        k--;
    }
    length=sizeof bal / sizeof bal[0];
    insertion_sort(bal, sizeof bal / sizeof bal[0]);
    printf("answerswer is = %2d",bal[length-1]);
}

我会做这样的事情:

  1. 创建地图以保存数据
  2. 成对阅读
  3. 对于 i = pair.first to pair.second ++map[i]
  4. 如果有更多对,请从 2 开始重复
  5. 在地图中查找计数最多的元素。该元素的关键是年份。

从理论上讲,您可以使用矢量而不是地图,但它的填充可能足够稀疏,以至于地图更有意义。