zoukankan      html  css  js  c++  java
  • leetcode: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"].

    分析:题意为 给定一个有序整型数组,返回总结区间,具体来说就是找出连续的序列,然后首尾两个数字之间用个“->"来连接,那么只需遍历一遍数组即可,每次检查下一个数是不是递增的,如果是,则继续往下遍历,如果不是了,我们还要判断此时是一个数还是一个序列,一个数直接存入结果,序列的话要存入首尾数字和箭头“->"。我们需要两个变量i和j,其中i是连续序列起始数字的位置,j是连续数列的长度,当j为1时,说明只有一个数字,若大于1,则是一个连续序列。

    代码如下:

    class Solution {
    public:
        vector<string> summaryRanges(vector<int>& nums) {
            vector<string> res;
            int i = 0, n = nums.size();
            while (i < n) {
                int j = 1;
                while (i + j < n && nums[i + j] - nums[i] == j) ++j;    //++j 加了再用,这也是后面j<=1,i+j-1的原因
                res.push_back(j <= 1 ? to_string(nums[i]) : to_string(nums[i]) + "->" + to_string(nums[i + j - 1]));
                i += j;
            }
            return res;
        }
    };
    

    第一次提交时,粗心将nums[i + j] - nums[i] == j中的=少写了一个,成了赋值运算符,所以出错:lvalue required as left operand of assignment(左值要求作为转让的左操作数)--------要仔细,要仔细,要仔细

    其他解法:

     class Solution {
        public:
            vector<string> summaryRanges(vector<int>& nums) {
                int len = nums.size(), i, start ;
                vector<string> res;
    
                for(i=1, start=0;i<=len;++i)
                {
                    if(i==len || (nums[i-1] + 1)!=nums[i])
                    { // the current range is finished or it reaches the end of vector, write back
                        res.push_back(((i-1) ==start)? to_string(nums[start]): (to_string(nums[start])+"->"+to_string(nums[i-1])));
                        start = i;
                    }
                }
                return res;
            }
        };
    

      

     

  • 相关阅读:
    Linux文件结构
    磁盘分区
    BASH简介
    磁盘的基本概念
    Linux文件操作
    创建文件系统
    文件系统挂载
    一些常用命令
    asp.net创建PPT
    asp.net创建、删除、移动文件夹 文件
  • 原文地址:https://www.cnblogs.com/carsonzhu/p/4622598.html
Copyright © 2011-2022 走看看