• LeetCode(228) Summary Ranges


    题目

    Given a sorted integer array without duplicates, return the summary of its ranges.

    For example, given [0,1,2,4,5,7], return [“0->2”,”4->5”,”7”].

    分析

    题目要求很明显,要求对给定的一组有序整数序列按照连续性分组显示;

    一次遍历记录连续子序列的首尾元素,然后转换为string格式,整数和字符串格式类型转换需要特别注意INT_MIN时特殊处理;

    AC代码

    class Solution {
    public:
        vector<string> summaryRanges(vector<int>& nums) {
            if (nums.empty())
                return vector<string>();
    
            int sz = nums.size();
    
            vector<string> ret;
            int start = nums[0], end = nums[0];
            for (int i = 1; i < sz; ++i)
            {
                if (nums[i] == end + 1)
                    end = nums[i];
                else{
                    string tmp;
                    if (end == start)
                        tmp = IntToString(start);
                    else
                        tmp = IntToString(start) + "->" + IntToString(end);
    
                    ret.push_back(tmp);
    
                    start = nums[i];
                    end = nums[i];
                }
            }//for
    
            //加上最后一组
            string tmp;
            if (end == start)
                tmp = IntToString(start);
            else
                tmp = IntToString(start) + "->" + IntToString(end);
            ret.push_back(tmp);
    
            return ret;
        }
    
        string IntToString(long num)
        {
            if (num == 0)
                return "0";     
            else if (num == INT_MIN)
                return "-2147483648";       
            string str;
            bool flag = num < 0 ? false : true;
    
            num = abs(num);
            while (num)
            {
                char c = num % 10 + '0';
                num /= 10;
                str += c;
            }//while
            reverse(str.begin(), str.end());
    
            if (flag)
                return str;
            else
                return "-" + str;
        }
    };

    GitHub测试程序源码

  • 相关阅读:
    taro clock组件
    创建taro项目
    ts声明各种变量类型
    ts的数组/元组/type/interface
    使用styled-components初始化css
    Oracle profile含义、修改、新增
    JDK bin指令
    Nginx 设置忽略favicon.ico文件的错误日志
    nginx: [error] CreateFile() "D: ginx-1.14.2/logs/nginx.pid" failed 解决办法
    Nginx Windows详细安装部署教程
  • 原文地址:https://www.cnblogs.com/shine-yr/p/5214754.html
Copyright © 2020-2023  润新知