Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit a1b95a0

Browse files
修改题228的代码
1 parent cb0307f commit a1b95a0

File tree

1 file changed

+12
-16
lines changed

1 file changed

+12
-16
lines changed

‎228.汇总区间.cpp‎

Lines changed: 12 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -8,24 +8,20 @@
88
class Solution {
99
public:
1010
vector<string> summaryRanges(vector<int>& nums) {
11-
if (nums.empty()) return {};
12-
if (nums.size() == 1) return { to_string(nums[0]) };
1311
vector<string> ans;
14-
int prev = nums[0];
15-
for (int i = 1; i < nums.size(); i++) {
16-
if ((long)nums[i] - nums[i - 1] != 1) {
17-
if (prev != nums[i - 1])
18-
ans.push_back(to_string(prev) + string("->") + to_string(nums[i - 1]));
19-
else
20-
ans.push_back(to_string(prev));
21-
prev = nums[i];
12+
int i = 0;
13+
int n = nums.size();
14+
// 分组循环
15+
while (i < n) {
16+
int start = i;
17+
while (i < n-1 && nums[i] + 1 == nums[i + 1])
18+
i++;
19+
if (nums[i] == nums[start]) {
20+
ans.push_back(to_string(nums[i]));
21+
} else {
22+
ans.push_back(to_string(nums[start]) + string("->") + to_string(nums[i]));
2223
}
23-
}
24-
int last = nums[nums.size() - 1];
25-
if (prev != last) {
26-
ans.push_back(to_string(prev) + string("->") + to_string(last));
27-
} else {
28-
ans.push_back(to_string(last));
24+
i++;
2925
}
3026
return ans;
3127
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /