Leetcode 228: Summary Ranges

Posted Keep walking

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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"]

 

Example 2:

Input: [0,2,3,4,6,8,9]
Output: ["0","2->4","6","8->9"]

 1 public class Solution {
 2     public IList<string> SummaryRanges(int[] nums) {
 3         var result = new List<string>();
 4         var sb = new StringBuilder();
 5         
 6         int i = 0, j = 0;
 7         while (j < nums.Length)
 8         {
 9             if (sb.Length == 0)
10             {
11                 sb.Append(nums[i]);
12             }
13             else if (nums[j] != nums[j - 1] + 1)
14             {
15                 if (nums[j - 1] != nums[i])
16                 {
17                     sb.Append("->");
18                     sb.Append(nums[j - 1]);
19                 }
20 
21                 result.Add(sb.ToString());
22                 sb.Clear();
23                 i = j;
24                 j--;
25             }
26             
27             j++;
28         }
29         
30         if (sb.Length > 0)
31         {
32             if (i < nums.Length - 1)
33             {
34                 sb.Append("->");
35                 sb.Append(nums[nums.Length - 1]);
36             }
37             
38             result.Add(sb.ToString());
39         }
40         
41         return result;
42     }
43 }

 



以上是关于Leetcode 228: Summary Ranges的主要内容,如果未能解决你的问题,请参考以下文章

Leetcode 228: Summary Ranges

LeetCode --- 228. Summary Ranges 解题报告

#Leetcode# 228. Summary Ranges

leetcode-Summary Ranges-228

228. Summary Ranges

228. Summary Ranges