def summary_ranges(nums) summary = []; if nums.size == 0 return summary end if nums.size == 1 return summary << nums[0].to_s end head = nums[0] nums.each_index do |i| next if i == 0 if nums[i] == nums.last && nums[i] != nums[i - 1] + 1 && head == nums[i - 1] summary << nums[i - 1].to_s summary << nums[i].to_s elsif nums[i] == nums.last && nums[i] != nums[i - 1] + 1 && head != nums[i - 1] summary << "#{head}->#{nums[i - 1]}" summary << nums[i].to_s elsif nums[i] == nums.last && nums[i] == nums[i - 1] + 1 summary << "#{head}->#{nums[i]}" elsif nums[i] != nums[i - 1] + 1 && head == nums[i - 1] summary << nums[i - 1].to_s head = nums[i] elsif nums[i] != nums[i - 1] + 1 && head != nums[i - 1] summary << "#{head}->#{nums[i - 1]}" head = nums[i] end end summary end
vector<string> summaryRanges(vector<int>& nums) { size_t len = nums.size(); vector<string> summary; if (len == 0){ return summary; } if (len == 1){ summary.push_back(to_string(nums[0])); return summary; } auto begin = nums.front(); for (size_t i = 1; i < len; ++i){ if (nums[i] == nums.back() && nums[i] != nums[i - 1] + 1 && begin == nums[i - 1]){ summary.push_back(to_string(nums[i - 1])); summary.push_back(to_string(nums[i])); } else if (nums[i] == nums.back() && nums[i] != nums[i - 1] + 1 && begin != nums[i - 1]){ summary.push_back(to_string(begin) + "->" + to_string(nums[i - 1])); summary.push_back(to_string(nums[i])); } else if (nums[i] == nums.back() && nums[i] == (nums[i - 1] + 1)){ summary.push_back(to_string(begin) + "->" + to_string(nums[i])); } else if (nums[i] != nums[i - 1] + 1 && begin == nums[i - 1]){ summary.push_back(to_string(nums[i - 1])); begin = nums[i]; } else if (nums[i] != nums[i - 1] + 1 && begin != nums[i - 1]){ summary.push_back(to_string(begin) + "->" + to_string(nums[i - 1])); begin = nums[i]; } } return summary; }
时间: 2025-01-10 09:50:31