forked from KnowledgeCenterYoutube/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
228_Summary_Ranges
62 lines (53 loc) · 1.62 KB
/
228_Summary_Ranges
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
Leetcode 228: Summary Ranges
Detailed video explanation: https://youtu.be/AjE4x3Yh9xc
========================================================
C++:
----
class Solution {
public:
vector<string> summaryRanges(vector<int>& nums) {
vector<string> result;
int n = nums.size();
if(n == 0) return result;
int a = nums[0];
for(int i = 0; i < n; ++i){
if(i == n-1 || nums[i]+1 != nums[i+1]){
if(nums[i] != a) result.push_back(to_string(a) + "->" + to_string(nums[i]));
else result.push_back(to_string(a));
if(i != n-1) a = nums[i+1];
}
}
return result;
}
};
Java:
-----
class Solution {
public List<String> summaryRanges(int[] nums) {
List<String> result = new ArrayList();
int n = nums.length;
if(n == 0) return result;
int a = nums[0];
for(int i = 0; i < n; ++i){
if(i == n-1 || nums[i]+1 != nums[i+1]){
if(nums[i] != a) result.add(a + "->" + nums[i]);
else result.add(a + "");
if(i != n-1) a = nums[i+1];
}
}
return result;
}
}
Python3:
-------
class Solution:
def summaryRanges(self, nums: List[int]) -> List[str]:
result, n = [], len(nums)
if n == 0: return result
a = nums[0]
for i in range(n):
if i == n-1 or nums[i]+1 != nums[i+1]:
if nums[i] != a: result.append(str(a) + "->" + str(nums[i]))
else: result.append(str(a))
if i != n-1: a = nums[i+1]
return result