Re: [閒聊] 每日LeetCode已回收
https://leetcode.com/problems/summary-ranges/description/
228. Summary Ranges
給你一個有序整數陣列,如果相鄰的元素是連續的將他們合併,例如:[1,2,3] ==>
[1,3],並把合併過的陣列 [a,b] 依照下列格式轉成字串:
"a->b" if a != b
"a" if a == b
Example 1:
Input: nums = [0,1,2,4,5,7]
Output: ["0->2","4->5","7"]
Explanation: The ranges are:
[0,2] --> "0->2"
[4,5] --> "4->5"
[7,7] --> "7"
Example 2:
Input: nums = [0,2,3,4,6,8,9]
Output: ["0","2->4","6","8->9"]
Explanation: The ranges are:
[0,0] --> "0"
[2,4] --> "2->4"
[6,6] --> "6"
[8,9] --> "8->9"
思路:
1.維護一個雙指針,當相鄰元素相差不為1或已經走到底的時候把 l ~ r-1 範圍的數字
合併,並加入結果集。
Java Code:
-------------------------------------------
class Solution {
public List<String> summaryRanges(int[] nums) {
List<String> res = new ArrayList<>();
int n = nums.length;
int l = 0;
int r = 1;
while (r <= n) {
if (r == n || nums[r] - nums[r - 1] != 1) {
String range = nums[l] + (l == r - 1 ? "" : "->" + nums[r -
1]);
res.add(range);
l = r;
}
r++;
}
return res;
}
}
-------------------------------------------
--
https://i.imgur.com/bFRiqA3.jpg

--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 122.100.75.86 (臺灣)
※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1686559804.A.5D8.html
※ 編輯: Rushia (122.100.75.86 臺灣), 06/12/2023 16:50:58
推
06/12 16:53,
2年前
, 1F
06/12 16:53, 1F
討論串 (同標題文章)
完整討論串 (本文為第 345 之 719 篇):