Leetcode日记(5)

本文介绍了解决两个经典算法问题的方法:一是寻找能容纳最多水的两个容器,采用贪心算法思想从两边向中间遍历;二是将整数转换为罗马数字,通过设置数组对应关系并拆分整数实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Container With Most Water

问题描述

        Given n non-negative integers a1, a2, …, an, where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water.
        Note: You may not slant the container and n is at least 2.

分析

       可以使用分治法等求解,将问题的解看为三种情况:区间最左边,区间最右边,区间中间,递归的计算每个区间的解,然后整合起来。笔者这里求解的方法是利用贪心算法的思路,从两边开始向中间遍历,依次寻找height最高的两个求他们结果,然后与前一结果比较。

解答

class Solution {
public:
    int maxArea(vector<int>& height) {
        int result = 0;
        for (int i = 0, j = height.size() - 1; i < j; )
        {
            int area = 0;
            if (height[i] > height[j])
            {
                area =(j - i) * height[j];
                j--;
                while (height[j] < height[j + 1])
                    j--;
            }
            else
            {
                area =(j - i) * height[i];
                i++;
                while (height[i] < height[i - 1])
                    i++;
            }
            if (area > result)
                result = area;

        }
        return result;
    }
};

Integer to Roman

问题描述

        Given an integer, convert it to a roman numeral.
       Input is guaranteed to be within the range from 1 to 3999.

分析

       罗马数字中每个符号代表一个数字,设置两个数组分别对应这种关系,然后拆分整数并将对应的罗马符号连接起来即可。

解答

class Solution {
public:
    string intToRoman(int num) {
        const int radix[] = {1000, 900, 500, 400, 100, 90,50, 40, 10, 9, 5, 4, 1};
        const string symbol[] = {"M", "CM", "D", "CD", "C", "XC","L", "XL", "X", "IX", "V", "IV", "I"};
        string result = "";
        for (int i = 0; num > 0; i++) 
        {
            int count = num / radix[i];
            num %= radix[i];
            for ( ; count > 0; count--) 
                result += symbol[i];
        }
        return result;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值