LeetCode 228 Summary Ranges(值域)(*)

简介: 版权声明:转载请联系本人,感谢配合!本站地址:http://blog.csdn.net/nomasp https://blog.csdn.net/NoMasp/article/details/50611045 翻译给定一个无重复的已排序整型数组,返回其中范围的集合。
版权声明:转载请联系本人,感谢配合!本站地址:http://blog.csdn.net/nomasp https://blog.csdn.net/NoMasp/article/details/50611045

翻译

给定一个无重复的已排序整型数组,返回其中范围的集合。
例如 ,给定[0,1,2,4,5,7],返回["0->2","4-5","7"]。

原文

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"].

分析

首先判断nums的长度,小于1的话直接未添加任何元素的vector了。

否则从索引0开始一直遍历所有nums元素。对其进行相应的判断,如果下一个元素和当前元素是紧邻的就直接递增索引而不做其他操作。

代码中还是用了to_string函数来从整型构造字符串。

代码

C Plus Plus

class Solution {
public:
    vector<string> summaryRanges(vector<int>& nums) {
        vector<string> v;
        if (nums.size() < 1) return v;
        int index = 0, pos = 0;
        while (index < nums.size()) {
            if (index + 1 < nums.size() && nums[index + 1] == nums[index] + 1)
                index++;
            else {
                if (pos == index) {
                    v.push_back(to_string(nums[index]));
                }
                else {
                    v.push_back(to_string(nums[pos]) + "->" + to_string(nums[index]));
                }
                index++;
                pos = index;
            }
        }
        return v;
    }
};

Java

updated at 2016/08/29
    public List<String> summaryRanges(int[] nums) {
        List<String> ranges = new ArrayList<>();
        if (nums.length < 1) return ranges;
        int index = 0, pos = 0;
        while (index < nums.length) {
            if ((index + 1) < nums.length && nums[index + 1] == nums[index] + 1) {
                index++;
            } else {
                if (pos == index) {
                    ranges.add(String.valueOf(nums[index]));
                } else {
                    ranges.add(String.valueOf(nums[pos]) + "->" + String.valueOf(nums[index]));
                }
                index++;
                pos = index;
            }
        }
        return ranges;
    }
目录
相关文章
LeetCode 228. Summary Ranges
给定一个无重复元素的有序整数数组,返回数组区间范围的汇总。
49 0
LeetCode 228. Summary Ranges
[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-&gt;2","4-&gt;5","7"]. 解题思路 略 实现代码 C++: // Runtim
1070 0
[LeetCode] Summary Ranges
This problem is similar to Missing Ranges and easier than that one. The idea is to use two pointers to find the beginning and end of a range and then push it into the result.
872 0
[LeetCode] Missing Ranges
Problem Description: Given a sorted integer array where the range of elements are [lower, upper] inclusive, return its missing ranges.
786 0
|
15小时前
|
算法 C++
【刷题】Leetcode 1609.奇偶树
这道题是我目前做过最难的题,虽然没有一遍做出来,但是参考大佬的代码,慢慢啃的感觉的真的很好。刷题继续!!!!!!
8 0
|
15小时前
|
算法 索引
【刷题】滑动窗口精通 — Leetcode 30. 串联所有单词的子串 | Leetcode 76. 最小覆盖子串
经过这两道题目的书写,相信大家一定深刻认识到了滑动窗口的使用方法!!! 下面请大家继续刷题吧!!!
11 0