首页 > 代码库 > leetcode 163: Missing Ranges
leetcode 163: Missing Ranges
Missing Ranges
Total Accepted: 510 Total Submissions: 2300Given 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"].
[分析]
O(N) 扫一遍即可, 跟新LOWER,
[注意]
两层循环, 共用一个i时, 内层循环要注意判断边界条件.
[CODE]
public class Solution { public List<String> findMissingRanges(int[] A, int lower, int upper) { if(A==null) return null; List<String> res = new ArrayList<String>(); for(int i=0; i<A.length; i++) { while(i<A.length && A[i] == lower ) {lower++; i++;} if(i>=A.length) break; if(A[i] == lower+1) { res.add(String.valueOf(lower)); } else { res.add("" + lower + "->" + (A[i]-1) ); } lower = A[i] + 1; } if(lower == upper) { res.add(String.valueOf(lower)); } else if(lower < upper ){ res.add("" + lower + "->" + upper ); } return res; } }
leetcode 163: Missing Ranges
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。