C++ solution. change int into string; sort and then connect; not quite efficient because bubblingsort is used


  • 0
    1
    string largestNumber(vector<int>& nums) {
        vector<string> inter;  
        string result="";
        for(int i=0;i<nums.size();++i)
            inter.push_back(inttostring(nums[i]));  //change int into string and push them into a new vector
        sort(inter);        //sort all the string;
        if(inter[inter.size()-1][0]=='0'){   //special case: all the numbers are 0;
            result+='0';
            return result;
        }
        for(int i=inter.size()-1;i>=0;--i)   //connect all the nums together;
            result+= inter[i];
        return result;
    }
    
    string inttostring(int var){
        string result;
        if(var==0){
            result.push_back('0');
            return result;
        }
        while(var){
            int remain = var%10;
            var=var/10;
            result.push_back('0'+remain);
        }
        reverse(result.begin(),result.end());
        return result;
    }
    void sort(vector<string> &nums){     //sort all the string using bubbling sort, here quicksort is more suitable
        bool flag;
        for(int i=0;i<nums.size()-1;++i){
            flag=false;
            for(int j=0;j<nums.size()-1-i;++j){
                if(gt(nums[j],nums[j+1])){
                    string tmp=nums[j];
                    nums[j]=nums[j+1];
                    nums[j+1]=tmp;
                    flag=true;
                }
            }
            if(!flag) break;
        }
    }
    
    enter code here

Log in to reply
 

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