标签:
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"].
1). 为空,lower upper 之间关系。
2). lower A[0] 之间关系
3). A[i]~A[i+1] 之间关系
4). A[A.length-1] ~ upper 之间关系
string i_tos(int n) { string s=""; char buf[4]; s+=itoa(n,buf,10); return s; } vector<string> findMissingRanges(int A[], int n, int lower, int upper) { vector<string> res; string str=""; if(n==0) { if(upper-lower>=1) str+=i_tos(lower)+"->"+i_tos(upper); else str+=i_tos(lower); if(str!="")res.push_back(str); } if (lower<A[0]) { if(A[0]-lower>1)str+=i_tos(lower)+"->"+i_tos(A[0]-1); else str+=i_tos(lower); if(str!="")res.push_back(str); } for (int i=1;i<n;i++) { if(A[i]-A[i-1]>2) str+=i_tos(A[i-1]+1)+"->"+i_tos(A[i]-1); else if(A[i]-A[i-1]==2) str+=i_tos(A[i-1]+1); if(str!="")res.push_back(str); str=""; } if(upper>A[n-1]) { if(upper-A[n-1]>1) str+=i_tos(A[n-1]+1)+"->"+i_tos(upper); else str+=i_tos(upper); if(str!="")res.push_back(str); } return res; }
标签:
原文地址:http://www.cnblogs.com/Vae1990Silence/p/4278036.html