LeetCode [11-the container with the most water] LeetCode [12-integer to Roman numerals]

The container with the most water

Title description

Given n non-negative integers a1, a2, ..., an, each number represents a point (i, ai) in coordinates. Draw n vertical lines in the coordinates. The two endpoints of vertical line i are (i, ai) and (i, 0). Find two of the lines so that the container they form with the x-axis can hold the most water.
Insert picture description here

Problem-solving ideas

The meaning of this question is that the sum of the difference between the subscript and the value of the subscript corresponding to the array is the largest
. , Each time it compares the previously calculated area with the current one

Code

class Solution {
public:
    int maxArea(vector<int>& height) {
        int length = height.size();
        int left = 0;
        int right = length-1;
        int temp = 0;
        int res = 0; //保存结果
        while(left<right)
        {
            //两条边中最短的
            temp = min(height[left],height[right]);
            res  = max(res,(right-left)*temp);
            //如果最短的边是左边,则left++,否则right++
            if(temp == height[left])
            {
                left++;
            }
            else
            {
                right--;
            }
        }
        return res;
    }
};

Integer to roman numeral

Title description

Problem-solving ideas

Look up the tables one by one, and subtract the corresponding number every time a number is found, and add the corresponding Roman number to the result.
Find the correspondence table between Roman numbers and numbers
Insert picture description here

Code

class Solution {
public:
    string intToRoman(int num) {
        int values[]={1000,900,500,400,100,90,50,40,10,9,5,4,1};
        string reps[]={"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"};
        
        string res;
        for(int i=0; i<13; i++){
            while(num>=values[i]){
                num -= values[i];
                res += reps[i];
            }
        }
        return res;
    }
};
Published 253 original articles · praised 41 · 40,000+ views

Guess you like

Origin blog.csdn.net/liuyuchen282828/article/details/104616702