Given a sorted integer array where the range of elements are [lower, upper] inclusive, return its missing ranges.
For example, given [0, 1, 3, 50, 75], lower = 0 and upper = 99, return ["2", "4->49", "51->74", "76->99"].
思路分析:这题基本就是考察双指针的应用,从lower-1开始,遍历nums数组找出missing range,可以利用pre和cur一前一后两个指针移动实现。注意lower和upper的处理,lower可以比nums中最小的数大,upper可以比nums中最大的数小,所以考虑要周全。
参考Code(Book中的题目)
public List<String> findMissingRanges(int[] nums, int lower, int upper) { List<String> res = new ArrayList<String>(); int pre = lower - 1; for(int i = 0; i < nums.length; i++){ if(i == nums.length){ cur = upper + 1; } else cur = nums[i]; if(cur - pre >= 2){ int missStart = pre + 1; int missEnd = cur - 1; if(missEnd == missStart) res.add(missEnd); else res.add(missStart + "->" + missEnd); pre = cur; } else { pre = cur; } } return res; }
时间: 2024-10-20 13:27:02