LeetCode Algorithm 0011 - 0015

版权声明:本文为博主原创文章,转载请注明出处。 https://blog.csdn.net/darkrabbit/article/details/82805827

LeetCode Algorithm 0011 - 0015



0011 - Container With Most Water (Medium)

Problem Link: https://leetcode.com/problems/container-with-most-water/description/

Description

Given n non-negative integers a 1 , a 2 , , a n a_1, a_2, \ldots , a_n , where each represents a point at coordinate ( i , a i ) (i, a_i) . n n vertical lines are drawn such that the two endpoints of line i i is at ( i , a i ) (i, a_i) and ( i , 0 ) (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 n is at least 2.

question 11

The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49.

Example:

Input: [1,8,6,2,5,4,8,3,7]
Output: 49

Solution C++

#pragma once

#include "pch.h"

// Problem: https://leetcode.com/problems/container-with-most-water/description/

namespace P11ContainerWithMostWater
{
    class Solution
    {
        public:
        int maxArea(vector<int>& height)
        {
            int size = height.size();
            int area = 0;

            for (int l = 0, r = size - 1; l < r;)
            {
                area = max(area, min(height[l], height[r]) * (r - l));
                if (height[l] < height[r])
                {
                    l++;
                }
                else
                {
                    r--;
                }
            }

            return area;
        }
    };
}


0012 - Integer to Roman (Medium)

Problem Link: https://leetcode.com/problems/integer-to-roman/description/

Description

Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.

Symbol       Value
I             1
V             5
X             10
L             50
C             100
D             500
M             1000

For example, two is written as II in Roman numeral, just two one’s added together. Twelve is written as, XII, which is simply X + II. The number twenty seven is written as XXVII, which is XX + V + II.

Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used:

  • I can be placed before V (5) and X (10) to make 4 and 9.
  • X can be placed before L (50) and C (100) to make 40 and 90.
  • C can be placed before D (500) and M (1000) to make 400 and 900.

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

Example 1:

Input: 3
Output: "III"

Example 2:

Input: 4
Output: "IV"

Example 3:

Input: 9
Output: "IX"

Example 4:

Input: 58
Output: "LVIII"
Explanation: C = 100, L = 50, XXX = 30 and III = 3.

Example 5:

Input: 1994
Output: "MCMXCIV"
Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.

Solution C++

#pragma once

#include "pch.h"

// Problem: https://leetcode.com/problems/integer-to-roman/description/

namespace P12IntegerToRoman
{
    class Solution
    {
        public:
        string intToRoman(int num)
        {
            if (num < 1 || num > 3999)
            {
                return "";
            }

            unordered_map<int, string> map;
            map[1] = "I";
            map[5] = "V";
            map[10] = "X";
            map[50] = "L";
            map[100] = "C";
            map[500] = "D";
            map[1000] = "M";

            int len = to_string(num).size();
            string roman = "";

            while (num != 0)
            {
                len--;
                int dividend = (int)pow(10, len);
                int unit = num / dividend;
                num %= dividend;

                if (unit != 0)
                {
                    switch (unit)
                    {
                        case 1:
                        case 2:
                        case 3:
                            for (int i = 0; i < unit; i++)
                            {
                                roman += map[dividend];
                            }
                            break;
                        case 4:
                            roman += map[dividend];
                        case 5:
                            roman += map[5 * dividend];
                            break;
                        case 6:
                        case 7:
                        case 8:
                            roman += map[5 * dividend];
                            for (int i = 0; i < unit - 5; i++)
                            {
                                roman += map[dividend];
                            }
                            break;
                        case 9:
                            roman += map[dividend];
                            roman += map[dividend * 10];
                            break;
                    }
                }
            }

            return roman;
        }
    };
}


0013 - Roman to Integer (Easy)

Problem Link: https://leetcode.com/problems/roman-to-integer/description/

Description

Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.

Symbol       Value
I             1
V             5
X             10
L             50
C             100
D             500
M             1000

For example, two is written as II in Roman numeral, just two one’s added together. Twelve is written as, XII, which is simply X + II. The number twenty seven is written as XXVII, which is XX + V + II.

Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used:

  • I can be placed before V (5) and X (10) to make 4 and 9.
  • X can be placed before L (50) and C (100) to make 40 and 90.
  • C can be placed before D (500) and M (1000) to make 400 and 900.

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

Example 1:

Input: "III"
Output: 3

Example 2:

Input: "IV"
Output: 4

Example 3:

Input: "IX"
Output: 9

Example 4:

Input: "LVIII"
Output: 58
Explanation: C = 100, L = 50, XXX = 30 and III = 3.

Example 5:

Input: "MCMXCIV"
Output: 1994
Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.

Solution C++

#pragma once

#include "pch.h"

// Problem: https://leetcode.com/problems/roman-to-integer/description/

namespace P13RomanToInteger
{
    class Solution
    {
        public:
        int romanToInt(string s)
        {
            if (s.empty())
            {
                return 0;
            }

            unordered_map<char, int> map;
            map['I'] = 1;
            map['V'] = 5;
            map['X'] = 10;
            map['L'] = 50;
            map['C'] = 100;
            map['D'] = 500;
            map['M'] = 1000;

            int size = s.size();
            int num = 0;

            for (size_t i = 0; i < size; i++)
            {
                // error char.
                if (map.find(s[i]) == map.end())
                {
                    return 0;
                }

                if (i + 1 < size)
                {
                    // error char.
                    if (map.find(s[i + 1]) == map.end())
                    {
                        return 0;
                    }

                    if (map[s[i]] < map[s[i + 1]])
                    {
                        num += map[s[i + 1]] - map[s[i]];
                        i++;
                        continue;
                    }
                }

                num += map[s[i]];
            }

            return num;
        }
    };
}


0014 - Longest Common Prefix (Easy)

Problem Link: https://leetcode.com/problems/longest-common-prefix/description/

Description

Write a function to find the longest common prefix string amongst an array of strings.

If there is no common prefix, return an empty string "".

Example 1:

Input: ["flower","flow","flight"]
Output: "fl"

Example 2:

Input: ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.

Note:

All given inputs are in lowercase letters a-z.

Solution C++

#pragma once

#include "pch.h"

// Problem: https://leetcode.com/problems/longest-common-prefix/description/

namespace P14LongestCommonPrefix
{
    class Solution
    {
        public:
        string longestCommonPrefix(vector<string>& strs)
        {
            if (strs.empty())
            {
                return "";
            }

            if (strs.size() == 1)
            {
                return strs[0];
            }

#if false // normal
            string prefix = strs[0];

            for (size_t i = 1; i < strs.size(); i++)
            {
                while (strs[i].compare(0, prefix.size(), prefix) != 0)
                {
                    prefix = prefix.substr(0, prefix.size() - 1);
                    if (prefix.empty())
                    {
                        return "";
                    }
                }
            }

            return prefix;
#endif

#if true // 二叉树
            int minLen = INT_MAX;
            for (vector<string>::iterator it = strs.begin(); it != strs.end(); it++)
            {
                minLen = min(minLen, (int)(*it).size());
            }

            int left = 1;
            int right = minLen;

            while (left <= right)
            {
                int middle = (left + right) / 2;
                
                bool leftNode = false;
                string prefix = strs[0].substr(0, middle);
                for (size_t i = 1; i < strs.size(); i++)
                {
                    if (strs[i].compare(0, prefix.size(), prefix) != 0)
                    {
                        right = middle - 1;
                        leftNode = true;
                        break;
                    }
                }

                if (!leftNode)
                {
                    left = middle + 1;
                }
            }

            return strs[0].substr(0, (left + right) / 2);
#endif
        }
    };
}



0015 - 3Sum (Medium)

Problem Link: https://leetcode.com/problems/3sum/description/

Description

Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0 ? Find all unique triplets in the array which gives the sum of zero.

Note:

The solution set must not contain duplicate triplets.

Example:

Given array nums = [-1, 0, 1, 2, -1, -4],

A solution set is:
[
  [-1, 0, 1],
  [-1, -1, 2]
]

Solution C++

#pragma once

#include "pch.h"

// Problem: https://leetcode.com/problems/3sum/description/

namespace P15ThreeSum
{
    class Solution
    {
        public:
        vector<vector<int>> threeSum(vector<int>& nums)
        {
            // 出现次数
            unordered_map<int, unsigned> numCounts;
            for (vector<int>::iterator it = nums.begin(); it != nums.end(); it++)
            {
                if (numCounts.find(*it) == numCounts.end())
                {
                    numCounts[*it] = 1;
                }
                else
                {
                    numCounts[*it] += 1;
                }
            }

            // 初始化结果容器
            vector<vector<int>> result;
            if (numCounts.find(0) != numCounts.end() && numCounts[0] >= 3)
            {
                result.push_back({ 0, 0, 0 });
            }

            // 正数与负数
            vector<int> positives, negtives;
            for (unordered_map<int, unsigned>::iterator it = numCounts.begin(); it != numCounts.end(); it++)
            {
                if (it->first > 0)
                {
                    positives.push_back(it->first);
                }
                else if (it->first < 0)
                {
                    negtives.push_back(it->first);
                }
            }

            // 只有正数或只有负数
            if (positives.empty() || negtives.empty())
            {
                return result;
            }

            // 计算
            for (size_t i = 0; i < positives.size(); i++)
            {
                for (size_t j = 0; j < negtives.size(); j++)
                {
                    int p = positives[i];
                    int n = negtives[j];
                    int negTwoSum = -(p + n); // 为了等于0,需要加上的数

                    // 不存在这样的数
                    if (numCounts.find(negTwoSum) == numCounts.end())
                    {
                        continue;
                    }

                    if (negTwoSum < n)
                    {
                        result.push_back({ negTwoSum, n, p });
                    }
                    else if (negTwoSum == n)
                    {
                        // 需要的数字与负数相同,且存在1个以上
                        if (numCounts[n] > 1)
                        {
                            result.push_back({ n, n, p });
                        }
                    }
                    else if (negTwoSum == 0)
                    {
                        // 相加结果为0
                        result.push_back({ n, 0, p });
                    }
                    else if (negTwoSum == p)
                    {
                        // 需要的数字与正数相同,且存在1个以上
                        if (numCounts[p] > 1)
                        {
                            result.push_back({ n, p, p });
                        }
                    }
                    else if (negTwoSum > p)
                    {
                        result.push_back({ n, p, negTwoSum });
                    }
                }
            }

            return result;
        }
    };
}


猜你喜欢

转载自blog.csdn.net/darkrabbit/article/details/82805827