1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
| def rangePrint(nums): res = [] if not nums: return res ori = 0 preVal = nums[0]
for i in range(1, len(nums)): if nums[i] == preVal+1: preVal = nums[i] if nums[i] == preVal: continue else: if i - ori == 1: res.append(str(nums[ori])) else: if nums[ori] == preVal: res.append(str(nums[ori])) else: temp = str(nums[ori]) + "->" + str(preVal) res.append(temp) ori = i preVal = nums[i] if ori +1 != len(nums): res.append(str(ori)+"->"+str(nums[-1])) else: res.append(str(nums[-1])) return res
print rangePrint([1,2,3,4,5,5,7,7,8,9,11])
def rangesummary2(nums): def helper(nums, l, r): while l +1 < r: m = (l+r)/2 if nums[m] - nums[l] == m - l: l = m else: r = m return l res = [] i = 0
while i < len(nums): k = helper(nums, i, len(nums))
if i != k: res.append(str(nums[i])+"->"+str(nums[k])) else: res.append(str(nums[i])) i = k+1 return res print rangesummary2([1,2,3,4,4,5,6,8])
|