zoukankan      html  css  js  c++  java
  • 【leetcode】三个数的最大乘积

    /*快排后 取最小两个负数和最大正数乘积和最大三个正数乘积比较取较大值*/
    int cmp(const void* a, const void* b){
        return *(int*)a - *(int*)b;
    }
    int maximumProduct(int* nums, int numsSize){
        qsort(nums,numsSize,sizeof(int),cmp);
        int val1,val2;    
        val1 = nums[0]*nums[1]*nums[numsSize-1];
        val2 = nums[numsSize-1]*nums[numsSize-2]*nums[numsSize-3];    
        return (val1>val2)? val1: val2;
    }
    //线性扫描
    int maximumProduct(int* nums, int numsSize){
        int a = -1000;
        int b = -1000;
        int c = -1000;
        int d = 1000;
        int e = 1000;
        for(int i=0 ; i < numsSize ; i++){
            if(nums[i] < d){
                e = d;
                d = nums[i];
            } else if(nums[i] < e){
                e = nums[i];
            }
            if(nums[i] > c){
                a = b;
                b = c;
                c = nums[i];
            } else if(nums[i] > b){
                a = b;
                b = nums[i];
            } else if(nums[i] > a){
                a = nums[i];
            }
        }
        int result1 = a*b*c;
        int result2 = d*e*c;
        if(result1 > result2){
            return result1;
        }
        return result2;
    }
  • 相关阅读:
    标准输入输出
    UNIX基础概念
    phpstrom设置php环境
    nginx+php+swoole安装记录
    MySQL索引
    生成器来解决大文件读取,大数据下载
    PHP调优
    PHP-FPM详解
    远程登录服务器配置
    HTTPS配置
  • 原文地址:https://www.cnblogs.com/ganxiang/p/13698669.html
Copyright © 2011-2022 走看看