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
| func summaryRanges(nums []int) []string { var rStr []string if len(nums) == 0 { return rStr } var head, tail int head, tail = nums[0], nums[0] for i := 1; i < len(nums); i++ { if nums[i] != tail+1 { if head == tail { rStr = append(rStr, strconv.Itoa(head)) } else { rStr = append(rStr, strconv.Itoa(head)+"->"+strconv.Itoa(tail)) } head = nums[i] tail = nums[i] }else{
tail = nums[i] } } if head == tail { rStr = append(rStr, strconv.Itoa(head)) } else { rStr = append(rStr, strconv.Itoa(head)+"->"+strconv.Itoa(tail)) } return rStr }
func summaryRanges1(nums []int) []string { var rStr []string for i,j :=0,0; j<len(nums);{ if j+1 < len(nums) && nums[j+1] == nums[j]+1{ j++ continue } if i==j { rStr = append(rStr, strconv.Itoa(nums[i])) }else{ rStr = append(rStr, strconv.Itoa(nums[i]) + "->" + strconv.Itoa(nums[j])) } i = j+1 j++ } return rStr }
|