LeetCode刷题日记(Day4)

Problem 8. String to Integer (atoi)

  • 题目描述
    Implement atoi which converts a string to an integer.
    The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.
    The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.
    If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.
    If no valid conversion could be performed, a zero value is returned.

  • 解题思路
    此题较简单,主要有以下要注意的地方:

  1. 数字前面的空格要忽略;
  2. 如果第一个非空格字符不是数字,则返回0。如输入"words and 987",则输出0;
  3. 数字后面凡出现了非数字字符,则截断,如输入"4193 with words",则输出4193;
  4. 如果数字长度超过INT_MAX或INT_MIN,则返回INT_MAX或INT_MIN。如输入“-91283472332”,则输出-2147483648。
  • 代码实现
class Solution {
public:
    int myAtoi(string str) {
        int len = str.length();      
        if (len == 0) 
            return 0;
        int i = 0;
        long long res = 0;
        int flag = 1;
        while(str[i] == ' ')
            ++i;
        if (str[i] == '+')
            ++i;
        else if(str[i] == '-'){
            ++i;
            flag = -1;
        }
        while(i < len){
            if (str[i] >= '0' && str[i] <= '9'){
                res = res*10 + str[i] - '0';
                if (res > INT_MAX)
                    return (flag == 1)? INT_MAX : INT_MIN;
                ++i;
            }
            else break;
        }
        return res * flag;
    }
};

Problem 11. 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.

  • 解题思路

  1. 在给定的数组height中选择两个元素,令左边的元素为height[i],右边的元素为height[j],即求坐标轴上i, j, height[i], height[j]四点之间能够围成的最大矩形面积。暴力搜索的复杂度为O(n^2),这里给出一种O(n)复杂度的算法。
  2. 创建两个索引(指针或迭代器)i和j,分别初始化为height的首末元素,求围成的矩形面积。通过将i右移,j左移,直到i、j相遇为止的方式,不断更新最大面积。
  3. 如果height[i] > height[j],则j左移一位。因为如果i右移,则新的矩形不仅长度变小了,宽度也不会再增加(瓶颈为height[j]),求新的矩形面积并判断是否更新最大面积。
  4. 如果height[i] < height[j],则i右移一位。
  • 时间复杂度分析
    由于只对传入的height遍历了一次,故时间复杂度为O(n)。

  • 代码实现

class Solution {
public:
    int maxArea(vector<int>& height) {
        vector<int>::iterator i = height.begin(), j = height.end()-1;
        int area = 0;
        while(i != j){
            if (*i > *j){
                area = (j-i)*(*j) > area ? (j-i)*(*j) : area;
                j--;
            }
            else{
                area = (j-i)*(*i) > area ? (j-i)*(*i) : area;
                i++;
            }
        }
        return area;
    }
};

Problem 13. Roman to Integer

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

  • 解题思路

  1. 建立map<char, int>变量m,将罗马数字和阿拉伯数字的值绑定。如 m[‘I’] = 1,m[‘V’] = 5;
  2. 对传入的 s 进行遍历,如果 m[s[i]] < m[s[i+1]],则表示 m[s[i+1]] - m[s[i]](详情请查阅罗马数字规则);否则表示 m[s[i+1]] + m[s[i]];
  • 时间复杂度分析
    由于只对传入的height遍历了一次,故时间复杂度为O(n)。

  • 代码实现

class Solution {
public:
    int romanToInt(string s) {
        map<char, int> m;
        m['I'] = 1;
        m['V'] = 5;
        m['X'] = 10;
        m['L'] = 50;
        m['C'] = 100;
        m['D'] = 500;
        m['M'] = 1000;

        int num = 0;
        for (int i = 0; i < s.length()-1; ++i){
            if (m[s[i]] < m[s[i+1]]) num -= m[s[i]];
            else num += m[s[i]];
        }
        num += m[s[s.length()-1]];
        return num;
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_36348299/article/details/88365037