163:缺失的区间
This commit is contained in:
parent
3d8f37136e
commit
7cbc571cc9
54
src/main/java/leetcode/editor/cn/MissingRanges.java
Normal file
54
src/main/java/leetcode/editor/cn/MissingRanges.java
Normal file
@ -0,0 +1,54 @@
|
||||
//给定一个排序的整数数组 nums ,其中元素的范围在 闭区间 [lower, upper] 当中,返回不包含在数组中的缺失区间。
|
||||
//
|
||||
// 示例:
|
||||
//
|
||||
// 输入: nums = [0, 1, 3, 50, 75], lower = 0 和 upper = 99,
|
||||
//输出: ["2", "4->49", "51->74", "76->99"]
|
||||
//
|
||||
// Related Topics 数组 👍 78 👎 0
|
||||
|
||||
package leetcode.editor.cn;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
//163:缺失的区间
|
||||
public class MissingRanges {
|
||||
public static void main(String[] args) {
|
||||
Solution solution = new MissingRanges().new Solution();
|
||||
solution.findMissingRanges(new int[]{0, 1, 3, 50, 75}, 0, 99);
|
||||
}
|
||||
|
||||
//leetcode submit region begin(Prohibit modification and deletion)
|
||||
class Solution {
|
||||
public List<String> findMissingRanges(int[] nums, int lower, int upper) {
|
||||
int index = 0;
|
||||
List<String> list = new ArrayList<>();
|
||||
for (int i = lower; i <= upper; i++) {
|
||||
while (index < nums.length && nums[index] < i) {
|
||||
index++;
|
||||
}
|
||||
if (index == nums.length) {
|
||||
if (i == upper) {
|
||||
list.add("" + i);
|
||||
} else {
|
||||
list.add(i + "->" + upper);
|
||||
}
|
||||
break;
|
||||
}
|
||||
if (nums[index] > i) {
|
||||
if (nums[index] == i + 1) {
|
||||
list.add("" + i);
|
||||
} else {
|
||||
list.add(i + "->" + (nums[index] - 1));
|
||||
}
|
||||
i = nums[index];
|
||||
index++;
|
||||
}
|
||||
}
|
||||
return list;
|
||||
}
|
||||
}
|
||||
//leetcode submit region end(Prohibit modification and deletion)
|
||||
|
||||
}
|
@ -0,0 +1,8 @@
|
||||
<p>给定一个排序的整数数组 <em><strong>nums </strong></em>,其中元素的范围在 <strong>闭区间</strong> <strong>[<em>lower, upper</em>]</strong> 当中,返回不包含在数组中的缺失区间。</p>
|
||||
|
||||
<p><strong>示例:</strong></p>
|
||||
|
||||
<pre><strong>输入: </strong><strong><em>nums</em></strong> = <code>[0, 1, 3, 50, 75]</code>, <strong><em>lower</em></strong> = 0 和 <strong><em>upper</em></strong> = 99,
|
||||
<strong>输出: </strong><code>["2", "4->49", "51->74", "76->99"]</code>
|
||||
</pre>
|
||||
<div><div>Related Topics</div><div><li>数组</li></div></div><br><div><li>👍 78</li><li>👎 0</li></div>
|
Loading…
Reference in New Issue
Block a user