163:缺失的区间

This commit is contained in:
轩辕龙儿 2022-03-18 23:46:31 +08:00
parent 3d8f37136e
commit 7cbc571cc9
2 changed files with 62 additions and 0 deletions

View 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)
}

View File

@ -0,0 +1,8 @@
<p>给定一个排序的整数数组 <em><strong>nums&nbsp;</strong></em>,其中元素的范围在&nbsp;<strong>闭区间</strong>&nbsp;<strong>[<em>lower, upper</em>]</strong>&nbsp;当中,返回不包含在数组中的缺失区间。</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>[&quot;2&quot;, &quot;4-&gt;49&quot;, &quot;51-&gt;74&quot;, &quot;76-&gt;99&quot;]</code>
</pre>
<div><div>Related Topics</div><div><li>数组</li></div></div><br><div><li>👍 78</li><li>👎 0</li></div>