LeetCode(3),汇总区间

184 阅读1分钟

给定一个无重复元素的有序整数数组,返回数组区间范围的汇总。

示例 1:

输入: [0,1,2,4,5,7] 输出: ["0->2","4->5","7"] 解释: 0,1,2 可组成一个连续的区间; 4,5 可组成一个连续的区间。

示例 2:

输入: [0,2,3,4,6,8,9] 输出: ["0","2->4","6","8->9"] 解释: 2,3,4 可组成一个连续的区间; 8,9 可组成一个连续的区间。

解:

function summaryRanges($nums) {
	if(empty($nums))
		return [];
	$str=[];
	$head = $tail = $nums[0];
	array_shift($nums);
	foreach ($nums as $value) {
		if($value == $tail+1){
			$tail++;
			continue;
		}else{
			if($head==$tail)
				$str[] = (string)$head;			
			else
				$str[] = $head.'->'.$tail;
			$head=$tail=$value;
		}

	}
	if($head==$tail)
		$str[] = (string)$head;			
	else
	$str[] = $head.'->'.$tail;

	return $str;    
}