欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C++实现LeetCode(228.总结区间)

程序员文章站 2023-12-29 15:54:58
[leetcode] 228.summary ranges 总结区间given a sorted integer array without duplicates, return the summar...

[leetcode] 228.summary ranges 总结区间

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"]
explanation: 0,1,2 form a continuous range; 4,5 form a continuous range.

example 2:

input:  [0,2,3,4,6,8,9]
output: ["0","2->4","6","8->9"]
explanation: 2,3,4 form a continuous range; 8,9 form a continuous range.

credits:
special thanks to for adding this problem and creating all test cases.

这道题给定我们一个有序数组,让我们总结区间,具体来说就是让我们找出连续的序列,然后首尾两个数字之间用个“->"来连接,那么我只需遍历一遍数组即可,每次检查下一个数是不是递增的,如果是,则继续往下遍历,如果不是了,我们还要判断此时是一个数还是一个序列,一个数直接存入结果,序列的话要存入首尾数字和箭头“->"。我们需要两个变量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 && (long)nums[i + j] - nums[i] == j) ++j;
            res.push_back(j <= 1 ? to_string(nums[i]) : to_string(nums[i]) + "->" + to_string(nums[i + j - 1]));
            i += j;
        }
        return res;
    }
};

类似题目:

missing ranges

data stream as disjoint intervals 

参考资料:

https://leetcode.com/problems/summary-ranges/discuss/63451/9-lines-c%2b%2b-0ms-solution

https://leetcode.com/problems/summary-ranges/discuss/63219/accepted-java-solution-easy-to-understand

到此这篇关于c++实现leetcode(228.总结区间)的文章就介绍到这了,更多相关c++实现总结区间内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

上一篇:

下一篇: