Leetcode 第228题 Summary Ranges

来源:互联网 发布:监控windows资源 编辑:程序博客网 时间:2024/05/22 00:47

题目: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”].

    Credits:
    Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.

    Subscribe to see which companies asked this question


题目分析:

  • 通过判断是否连续,来判断字符串应该如何表达

代码:

  • Javascript
Javascript:[byself]/** * @param {number[]} nums * @return {string[]} */var summaryRanges = function(nums) {    var arr=[];//arr用于存放最后返回的数组    var front=0;//范围开始的第一个数字    var temp=0;//范围开始的最后一个数字    var i=0;    var j=0;//是范围开始的数字的index    var cont=0;//如果cont是0 那么代表含义是这个数字前后断开,单独字符串 ; 如果cont不是零,那么代表字符串类似1->2    while(i<nums.length)    {        front=nums[j];        temp=nums[i];        if(i+1<nums.length && nums[i+1]==temp+1)//如果i不是倒数第二个,并且满足数组中前后两个数字之间是连续的        {            i++;            cont++;        }        else//如果i是倒数第二个或数组中前后两个数值之间不是连续的        {            var str='';            if(cont==0)//通过cont来区分是单个数字组成字符串还是连续数字范围构成的字符串            {                str+=front;                arr.push(str);            }            else            {                str+=front+"->"+temp;                arr.push(str);            }            j=i+1;            i++;            cont=0;        }    }    return arr;};
  • C++:[代码参考别人的,不是很懂C++语法,但是算法思路自己想的]
class Solution {public:    vector<string> summaryRanges(vector<int>& nums) {        vector<string> result;          if (nums.size()<1)              return result;          int begin, end;          begin = end = nums[0];          for (int i=1; i<nums.size(); i++)          {              if (nums[i] ==end || nums[i]==end+1)              {                  end = nums[i];              }               else              {                  result.push_back(format(begin, end));                  begin = end = nums[i];              }          }          result.push_back(format(begin, end));          return result;     }    string format(int begin, int end)      {          char buffer[32];          if (end == begin)          {              sprintf(buffer, "%d", begin);          }else{              sprintf(buffer, "%d->%d", begin, end);          }          return string(buffer);      }  };
0 0