zoukankan      html  css  js  c++  java
  • leetcode 228. Summary Ranges

     

    You are given a sorted unique integer array nums.

    Return the smallest sorted list of ranges that cover all the numbers in the array exactly. That is, each element of nums is covered by exactly one of the ranges, and there is no integer x such that x is in one of the ranges but not in nums.

    Each range [a,b] in the list should be output as:

    • "a->b" if a != b
    • "a" if a == b

    Example 1:

    Input: nums = [0,1,2,4,5,7]
    Output: ["0->2","4->5","7"]
    Explanation: The ranges are:
    [0,2] --> "0->2"
    [4,5] --> "4->5"
    [7,7] --> "7"
    

    Example 2:

    Input: nums = [0,2,3,4,6,8,9]
    Output: ["0","2->4","6","8->9"]
    Explanation: The ranges are:
    [0,0] --> "0"
    [2,4] --> "2->4"
    [6,6] --> "6"
    [8,9] --> "8->9"
    

    Example 3:

    Input: nums = []
    Output: []
    

    Example 4:

    Input: nums = [-1]
    Output: ["-1"]
    

    Example 5:

    Input: nums = [0]
    Output: ["0"]
    

    Constraints:

    • 0 <= nums.length <= 20
    • -231 <= nums[i] <= 231 - 1
    • All the values of nums are unique.

    题目难度:简单题

    C++代码:

     1 class Solution {
     2 public:
     3     vector<string> summaryRanges(vector<int>& nums) {
     4         vector<string> vec;
     5         string s;
     6         int j;
     7         // i指向连续range数组的第一个数,j一开始指向i下一个,如果一直是相邻的,则j一直往后移,直到j指向第一个不属于range数组的数。
     8         for (int i = 0; i < nums.size();) {
     9             j = i + 1;
    10             while (j < nums.size()){
    11                 if (nums[j - 1] + 1 != nums[j])
    12                     break;
    13                 ++j;
    14             }
    15             //这种情况表示i指向的range数组只有一个数。
    16             if (j - i == 1) {
    17                 s = to_string(nums[i]);
    18             } else {
    19                 s = to_string(nums[i]) + "->" + to_string(nums[j - 1]);
    20             }
    21             vec.push_back(s);
    22             i = j; //i指向下一个range数组
    23         }
    24         return vec;
    25     }
    26 };

    时间复杂度:$O(n)$


    python3代码:

    1 class Solution:
    2     def summaryRanges(self, nums: List[int]) -> List[str]:
    3         ranges = []
    4         for n in nums:
    5             if not ranges or n > ranges[-1][-1] + 1:
    6                 ranges += [], // 最后的,很重要
    7             ranges[-1][1:] = n, //最后的,很重要
    8         return ['->'.join(map(str, r)) for r in ranges]
  • 相关阅读:
    HD2058The sum problem
    采用循环链表结构求解约瑟夫问题
    java线性表学习笔记(二)
    java线性表学习笔记(一)
    HD1004Let the Balloon Rise
    HD1005Number Sequence
    用c++库函数轻松解决回文问题
    accelerated C++ 中查找url(学习笔记)
    C++ 之关联容器 map
    pytorch 迁移学习[摘自官网]
  • 原文地址:https://www.cnblogs.com/qinduanyinghua/p/13897786.html
Copyright © 2011-2022 走看看