【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 41 First Missing PositiveLeetCode
- [LeetCode] 2028. Find Missing ObservationsLeetCode
- 228. Summary Ranges
- CF1456E XOR-ranges
- Kotlin中的Ranges以及自定義RangeKotlin
- 題解:CF1623B Game on RangesGAM
- Pandas fillna('Missing')
- Missing Subsequence Sum
- [LeetCode Python3] 41. First Missing Positive 一步步優化LeetCodePython優化
- New Type Functions/Utilities for Dealing with Ranges in C++20FunctionC++
- missing ) after argument list
- find: missing argument to `-exec'
- Missing MSI and MSP files
- your Android sdk is missingAndroid
- gerrit "missing Change-Id"
- OPatch install "Missing command :fuser"
- B. Missing Subsequence Sum
- GAMES001&mit missing semesterGAMMIT
- shell指令碼報錯:[: missing `]‘指令碼
- Dynamic Web Project option missing in Eclipse KeplerWebProjectEclipse
- keil error:#8:missing closing quote 處理Error
- [ARC186E] Missing Subsequence 題解
- Laravel 8 路由模組新增 missing 方法Laravel路由
- [20230508]ORA-00907 missing right parenthesis.txt
- Java報錯:Missing ServletWebServerFactory bean,如何解決JavaServletWebServerBean
- 【Android】Permission denied (missing INTERNET permission?)異常踩坑Android
- LOGSTDBY status: ORA-16227: DDL skipped due to missing objectObject
- SAP How to maintain missing enrties in TJ07 via customizingAI
- 【問題解決】property [elasticsearch.version] is missing for plugin [head]ElasticsearchPlugin
- git clone 報錯 “URL using bad/illegal format or missing URL“GitORM
- Node.js 中 TypeError [ERR_IMPORT_ASSERTION_TYPE_MISSING]Node.jsErrorImport
- OGG-01028 Recovery record is missing from log 的BUG處理
- Missing key(s) in state_dict: Unexpected key(s) in state_dict
- 【BUG】Oracle12c tablespace io statistics missing from awr reportOracle
- .lastUpdated:The POM for mysql:mysql-connector-java:jar:8.1.0 is missing, no dependency information availableASTMySqlJavaJARORMAI
- SAP對物料做上架報錯 :Definition of totals level is missing for storage type
- 修改sys密碼報錯:ORA-01994: Password file missing or disabled密碼
- Python成功解決TypeError: __init__() missing 1 required positional argument: ‘comment‘PythonErrorUI