博客
关于我
已知f[]与g[]两个整数数组,元素都已经 从小到大排好序, 请写一个程序,算出f[]中比g[]中元素大的对数。
阅读量:242 次
发布时间:2019-03-01

本文共 1181 字,大约阅读时间需要 3 分钟。

为了解决这个问题,我们需要计算两个已排序整数数组 f 和 g 中的元素,使得 f 中的每个元素比 g 中的多少个元素大,并将这些数量累加起来。

方法思路

我们可以使用双指针技术来高效地解决这个问题。具体步骤如下:

  • 初始化两个指针 i 和 j,分别从 f 和 g 的开头开始。
  • 遍历 g 数组中的每个元素 g[j]。
  • 对于每个 g[j],找到 f 中第一个大于 g[j] 的元素的位置。
  • 每找到一个这样的位置,计算 g[j] 之后比它大的 f 元素的数量,并累加到总和中。
  • 这种方法的时间复杂度是 O(m + n),其中 m 和 n 分别是 f 和 g 的长度。这种线性时间复杂度使得算法非常高效。

    解决代码

    #include 
    #include
    int main() { int m, n; while (scanf("%d %d", &m, &n) != EOF) { int *f = malloc(m * sizeof(int)); int *g = malloc(n * sizeof(int)); for (int i = 0; i < m; ++i) { scanf("%d", f + i); } for (int i = 0; i < n; ++i) { scanf("%d", g + i); } int i = 0, sum = 0; for (int j = 0; j < n; ++j) { while (i < m && f[i] <= g[j]) { ++i; } sum += m - i; } printf("%d\n", sum); free(f); free(g); } return 0;}

    代码解释

  • 读取输入:首先读取两个整数 m 和 n,分别表示数组 f 和 g 的长度。
  • 读取数组:使用 malloc 分配内存,读取并存储 f 和 g 数组的元素。
  • 初始化指针:使用两个指针 i 和 j,分别从 f 和 g 的开头开始。
  • 遍历 g 数组:对于每个 g[j],使用 while 循环找到 f 中第一个大于 g[j] 的元素的位置。
  • 计算和累加:每找到一个这样的位置,计算 g[j] 之后比它大的 f 元素的数量,并累加到总和中。
  • 输出结果:打印累加的结果。
  • 这种方法确保了在 O(m + n) 时间复杂度内高效地解决问题,适用于较大的数组长度。

    转载地址:http://gjzt.baihongyu.com/

    你可能感兴趣的文章
    NMF(非负矩阵分解)
    查看>>
    NN&DL4.1 Deep L-layer neural network简介
    查看>>
    NN&DL4.3 Getting your matrix dimensions right
    查看>>
    NN&DL4.8 What does this have to do with the brain?
    查看>>
    No 'Access-Control-Allow-Origin' header is present on the requested resource.
    查看>>
    No Datastore Session bound to thread, and configuration does not allow creation of non-transactional
    查看>>
    No fallbackFactory instance of type class com.ruoyi---SpringCloud Alibaba_若依微服务框架改造---工作笔记005
    查看>>
    No Feign Client for loadBalancing defined. Did you forget to include spring-cloud-starter-loadbalanc
    查看>>
    No mapping found for HTTP request with URI [/...] in DispatcherServlet with name ...的解决方法
    查看>>
    No module named cv2
    查看>>
    No module named tensorboard.main在安装tensorboardX的时候遇到的问题
    查看>>
    No module named ‘MySQLdb‘错误解决No module named ‘MySQLdb‘错误解决
    查看>>
    No new migrations found. Your system is up-to-date.
    查看>>
    No qualifying bean of type XXX found for dependency XXX.
    查看>>
    No resource identifier found for attribute 'srcCompat' in package的解决办法
    查看>>
    No toolchains found in the NDK toolchains folder for ABI with prefix: mips64el-linux-android
    查看>>
    NO.23 ZenTaoPHP目录结构
    查看>>
    NO32 网络层次及OSI7层模型--TCP三次握手四次断开--子网划分
    查看>>
    NoClassDefFoundError: org/springframework/boot/context/properties/ConfigurationBeanFactoryMetadata
    查看>>
    Node JS: < 一> 初识Node JS
    查看>>