LeetCode 228 Summary Ranges(值域)(*)

翻译

给定一个无重复的已排序整型数组,返回其中范围的集合。
例如 ,给定[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;
    }
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值