【Leetcode】163. Missing Ranges
題目地址:
https://leetcode.com/problems/missing-ranges/
給定一個無重複數字的長
n
n
n升序陣列
A
A
A,再給定一個區間
[
l
,
u
]
[l,u]
[l,u],題目保證
l
≤
A
[
0
]
,
A
[
n
−
1
]
≤
r
l\le A[0], A[n-1]\le r
l≤A[0],A[n−1]≤r。求所有
[
l
,
r
]
−
A
[l,r]-A
[l,r]−A所剩的區間族。如果區間是單元集則就是它一個數,否則寫成"a->b"
的形式。
程式碼如下:
import java.util.ArrayList;
import java.util.List;
public class Solution {
public List<String> findMissingRanges(int[] nums, int lower, int upper) {
List<String> res = new ArrayList<>();
int start = lower;
for (int i = 0; i < nums.length; i++) {
if (nums[i] == start) {
start = nums[i] + 1;
continue;
}
if (nums[i] == start + 1) {
res.add(String.valueOf(start));
} else if (nums[i] > start + 1) {
res.add(start + "->" + (nums[i] - 1));
}
start = nums[i] + 1;
}
if (start == upper) {
res.add(String.valueOf(start));
} else {
res.add(start + "->" + upper);
}
return res;
}
}
時間複雜度 O ( n ) O(n) O(n),空間 O ( 1 ) O(1) O(1)。
相關文章
- Leetcode-Missing RangesLeetCode
- LeetCode-Summary RangesLeetCode
- LeetCode:Missing Number And First Missing PositiveLeetCode
- 【LeetCode 228_陣列】Summary RangesLeetCode陣列
- Leetcode First Missing PositiveLeetCode
- Leetcode 41 First Missing PositiveLeetCode
- Leetcode-First Missing PositiveLeetCode
- First Missing Positive leetcode javaLeetCodeJava
- [LeetCode] 2028. Find Missing ObservationsLeetCode
- Kotlin中的Ranges以及自定義RangeKotlin
- 題解:CF1623B Game on RangesGAM
- Missing Subsequence Sum
- ntldr is missing怎麼解決? ntldr is missing怎麼回事?
- New Type Functions/Utilities for Dealing with Ranges in C++20FunctionC++
- First Missing Positive【hard】
- [LeetCode Python3] 41. First Missing Positive 一步步優化LeetCodePython優化
- gerrit "missing Change-Id"
- your Android sdk is missingAndroid
- NILDR is Missing解決方案
- B. Missing Subsequence Sum
- PB協議報錯 it is missing required fields: (cannot determine missing fields for lite message)協議UI
- shell指令碼報錯:[: missing `]‘指令碼
- 【Python】 Missing parentheses in call to 'print'Python
- Laravel 8 路由模組新增 missing 方法Laravel路由
- ntldr is missing問題如何解決?
- GAMES001&mit missing semesterGAMMIT
- Dynamic Web Project option missing in Eclipse KeplerWebProjectEclipse
- Missing Microsoft.CompactFramework.CSharp.targetsROSFrameworkCSharp
- Missing com.sun.jdmk:jmxtools:jar:1.2.1JAR
- keil error:#8:missing closing quote 處理Error
- DQACP is missing Press Ctrl+Alt+Del to Restart(圖)REST
- [ARC186E] Missing Subsequence 題解
- Java報錯:Missing ServletWebServerFactory bean,如何解決JavaServletWebServerBean
- Your PHP installation appears to be missing the MySQL extension which is requirePHPAPPMySqlUI
- [CareerCup] 5.7 Find Missing Integer 查詢丟失的數
- GK659 Missing item assignment for 'Minority interest in the balance sheet'REST
- OGG-01028 Recovery record is missing ERRORError
- Oracle OCP IZ0-053(Recovery Missing Active Redo Log)Oracle