已知数组 a = [0,1,2,3,5,7,8,9]
要求输入其“概览” [0..3,5,7..9]
用ruby实现如下:
def sum_ary(ary)
tmp = []
start_v,end_v=-1,-1
is_start = false
idx = 0
count = ary.count
ary.each_with_index do |v,i|
if(i+1<count)
sub = ary[i+1] - v
if(sub == 1)
if(is_start)
next
else
is_start = true
start_v = v
end
else
if(is_start)
is_start = false
end_v = v
tmp.push(Range.new(start_v,end_v))
else
tmp.push(v)
end
end
else
#condition for i+1>=count
if(is_start)
is_start = false
end_v = v
tmp.push(Range.new(start_v,end_v))
else
tmp.push(v)
end
end
end
tmp
end
时间: 2024-10-12 10:52:40