My C++ solution , where is the performance bottlenecks?


  • 0
    A

    Runtime: 0 ms
    Your runtime beats 1.50% of cpp submissions.

    class Solution {
    private:
        vector < string > data{};
        
        class Helper{
            int start;
            int end;
            
            // step : 0 -> there is no number
            //           1 -> start has set
            //           2 -> end has set
            int step = 0;
            vector < string > & data;
        public:
            Helper ( vector < string > & d ) :data ( d ) {}
            void push ( int n ) {
                if ( step == 0 ) {
                    start = n ;
                    step = 1;
                }
                else if ( step == 1 ) {
                    if ( start + 1 == n ) {
                        end = n;
                        step = 2;
                    }
                    else{
                        data.push_back ( to_string ( start ) ) ;
                        start = n;
                        step = 1;
                    }
                }
                else if ( step == 2 ) {
                    if ( end + 1 == n ) {
                        end = n;
                    }
                    else{
                        data.push_back ( to_string ( start ) + "->" + to_string ( end ) ) ;
                        start = n;
                        step = 1;
                    }
                }
            }
            ~Helper ( ) {
                if ( step == 1 ) {
                    data.push_back ( to_string ( start ) ) ;
                }
                else if ( step == 2 ) {
                    data.push_back ( to_string ( start ) + "->" + to_string ( end ) ) ;
                }
            }
            
        };
    public:
        vector < string > summaryRanges ( vector < int > & nums ) {
            Helper * h = new Helper ( data ) ;
            for ( auto n : nums ) {
                h -> push ( n ) ;
            }
            delete h;
            return data;
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.