leetcode 228. Summary Ranges

来源:互联网 发布:silverlight.js 编辑:程序博客网 时间:2024/05/17 22:26

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

Example 1:
Input: [0,1,2,4,5,7]
Output: [“0->2”,”4->5”,”7”]
Example 2:
Input: [0,2,3,4,6,8,9]
Output: [“0”,”2->4”,”6”,”8->9”]

就是寻找连续的序列,遍历即可。

代码如下:

import java.util.ArrayList;import java.util.List;/* * 这个题很简单,不过要注意超出int表示范围的问题 * 只需要一次遍历即可 * */public class Solution {    public List<String> summaryRanges(int[] nums)     {        List<String> res=new ArrayList<String>();        int i=0;        while(i<nums.length)        {            int beg=nums[i];            int j=i+1;            for(;j<nums.length;j++)            {                //注意这里使用的是!=而不是>,因为可能出现一个极大的数减去一个极小的负数,、                //这样int越界,所以这里使用了不等号处理                if(nums[j]-nums[j-1]!=1)                    break;              }            if(j==i+1)                res.add(beg+"");            else                 res.add(beg+"->"+nums[j-1]);            i=j;        }               return res;    }}

下面是C++的做法,就是一个简单的循环遍历的做法

代码如下:

#include <iostream>#include <algorithm>#include <vector>#include <set>#include <string>#include <map>using namespace std;class Solution {public:    vector<string> summaryRanges(vector<int>& nums)     {        vector<string> res;        int i = 0;        while (i < nums.size())        {            int now = nums[i];            int j = 0;            for (j = i + 1; j < nums.size(); j++)            {                if (nums[j] != nums[j - 1] + 1)                    break;            }            if (j == i + 1)                res.push_back(to_string(now));            else                res.push_back(to_string(now) + "->" + to_string(nums[j - 1]));            i = j;        }        return res;    }};