博客
关于我
遍历数组寻找符合条件的数:力扣(414、628)
阅读量:693 次
发布时间:2019-03-17

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

一、母题:求第三大数

在求解数组中的第三大数问题时,我们需要定义多个变量来存储前几大的数。例如,第三大的数可以通过以下方式实现:

  • 定义变量:使用三个变量分别存储前三个最大的数,max1max2max3,其中 max1 是最大值,max2 是第二大值,max3 是第三大值。
  • 处理重复值:在遍历数组时,如果某个值等于现有的最大值,则跳过。
  • 更新变量:根据当前数与现有最大值的关系,更新变量,例如:
    • 如果当前数大于 max1,则 max3 替换 max2max2 替换 max1max1 更新为当前数。
    • 如果当前数介于 max2max1 之间,则 max3 替换 max2max2 更新为当前数。
    • 如果当前数小于 max2 但大于 max3,则 max3 更新为当前数。
  • 二、变体:求最大乘积

    在变体问题中,我们需要考虑数组中既有正数也有负数的情况。这种情况下,我们需要遍历数组,分别找出最大的三个数和最小的两个数(因为负数的绝对值较大的数实际上是更小的数)。最终,最大乘积可能来自以下两种情况:

  • 最大的三个正数。
  • 最大的一个正数和最小的一个负数的二次方的结果。
  • 解决方案如下:

  • 定义变量:使用 max1max2max3 来存储前三个最大的数,以及 min1min2 来存储最小的两个数。
  • 遍历数组:在遍历过程中,判断每个数是最大值还是最小值,并更新相应的变量。
  • 计算乘积:最后比较两个可能的乘积(三个最大的数的乘积和最大正数与最小负数的乘积),返回最大的那个值。
  • 代码示例

    public int maximumProduct(int[] nums) {    int max1 = Integer.MIN_VALUE, max2 = Integer.MIN_VALUE, max3 = Integer.MIN_VALUE;    int min1 = Integer.MAX_VALUE, min2 = Integer.MAX_VALUE;        for (int num : nums) {        // 处理最大值部分        if (num > max1) {            max3 = max2;            max2 = max1;            max1 = num;        } else if (num > max2) {            max3 = max2;            max2 = num;        } else if (num > max3) {            max3 = num;        }                // 处理最小值部分        if (num < min1) {            min2 = min1;            min1 = num;        } else if (num < min2) {            min2 = num;        }    }    return Math.max(max1 * max2 * max3, min1 * min2 * max1);}

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

    你可能感兴趣的文章
    npm和package.json那些不为常人所知的小秘密
    查看>>
    npm和yarn清理缓存命令
    查看>>
    npm和yarn的使用对比
    查看>>
    npm如何清空缓存并重新打包?
    查看>>
    npm学习(十一)之package-lock.json
    查看>>
    npm安装 出现 npm ERR! code ETIMEDOUT npm ERR! syscall connect npm ERR! errno ETIMEDOUT npm ERR! 解决方法
    查看>>
    npm安装crypto-js 如何安装crypto-js, python爬虫安装加解密插件 找不到模块crypto-js python报错解决丢失crypto-js模块
    查看>>
    npm安装教程
    查看>>
    npm报错Cannot find module ‘webpack‘ Require stack
    查看>>
    npm报错Failed at the node-sass@4.14.1 postinstall script
    查看>>
    npm报错fatal: Could not read from remote repository
    查看>>
    npm报错File to import not found or unreadable: @/assets/styles/global.scss.
    查看>>
    npm报错TypeError: this.getOptions is not a function
    查看>>
    npm报错unable to access ‘https://github.com/sohee-lee7/Squire.git/‘
    查看>>
    npm淘宝镜像过期npm ERR! request to https://registry.npm.taobao.org/vuex failed, reason: certificate has ex
    查看>>
    npm版本过高问题
    查看>>
    npm的“--force“和“--legacy-peer-deps“参数
    查看>>
    npm的安装和更新---npm工作笔记002
    查看>>
    npm的常用操作---npm工作笔记003
    查看>>
    npm的常用配置项---npm工作笔记004
    查看>>