0
点赞
收藏
分享

微信扫一扫

数据结构-线性表(数组)-线性枚举中最值算法 1464

一ke大白菜 2022-03-26 阅读 27

数据结构:数组
算法:线性枚举
目标:求最大值

原始算法
思路就是求解数组nums中最大值和次大值

class Solution 
{
public:
    int maxProduct(vector<int>& nums) 
    {
        int len = nums.size();
        int max = (nums[0]-1)*(nums[1]-1);
        int temp;
        for(int i = 0;i < len; ++i)
        {
            for(int j = i+1;j<len;++j)
            {
                temp = (nums[i]-1)*(nums[j]-1);
                if(temp>max)
                {
                    max = temp;
                }
            }
        }
        return max;
    }
};

使用STL库

class Solution 
{
public:
    int maxProduct(vector<int>& nums) 
    {
        int len = nums.size();
        sort(nums.begin(),nums.end());
        return (nums[len-1]-1)*(nums[len-2]-1);

    }
};

看了英雄哥的求数组nums中最大值和次大值

class Solution {
public:
    int maxProduct(vector<int>& nums) {
        int len = nums.size();
        int max = 0;
        int nextmax = 0;
        for(int i = 0;i<len;++i){
            if(nums[i]>max){
                nextmax = max;
                max = nums[i];
            }
            else if(nums[i]>nextmax){
                nextmax = nums[i];
            }
        }
        return (max-1) * (nextmax-1);
    }
};
举报

相关推荐

0 条评论