LeetCode Summary Ranges

本文介绍了一种算法,用于处理已排序且无重复元素的整数数组,返回数组中连续子序列的汇总。通过使用双指针技巧,该方法能够有效地找到连续的数字范围并将其格式化为指定形式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:

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

题意:

在一个已经排好序的没有重复的数组中,现在要求其中连续的子序列,如上面给的例子那样。此题也有那么一点难度。我们可以看到主要是运用下标来表示,考虑用两个指针来指示,一个是start,另一个是end。如果发现,nums[end+1] == nums[end] + 1,那么就将这个end后移,一开始,end等于start。每次执行这个操作,也得分情况,如果某一个连续的数字成单的,那么直接存入这个list即可,否则end一直走,直到碰到第一个不连续的数字位置。

public static List<String> summaryRanges(int[] nums)
	{
		int length = nums.length;
		List<String> list = new ArrayList<String>();
		if(length == 0 || nums == null)
			return list;
		int i = 0;
		int s = 0;
		while(i < length)
		{
			if(i + 1 < length && nums[i+1] == nums[i] + 1)
			{
				i++;
			}
			else 
			{
				if(s == i)
					list.add(Integer.toString(nums[s]));
				else
				{
					String str = nums[s] + "->" + nums[i];
					list.add(str);
				}
				i = i + 1;
				s = i;
			}
		}
		return list;
	}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值