179. Largest Number

Difficulty: Medium

Frequency: N/A

Given a list of non negative integers, arrange them such that they form the largest number.

For example, given [3, 30, 34, 5, 9], the largest formed number is 9534330.

Note: The result may be very large, so you need to return a string instead of an integer.


My solution:
Data structure:
Steps:
Complexity:
Runtime:
Space:
Test cases:
Corner cases:
Code:
class Solution {
public:
    string largestNumber(vector<int>& nums) {
        sort(nums.begin(), nums.end(), compare);
        string result;
        for (int i = nums.size() - 1; i >= 0; i--) {
            result += to_string(nums[i]);
        }
        if (result.find_first_not_of('0') == string::npos) return "0";
        else return result = result.substr(result.find_first_not_of('0'));
    }
private:
    static bool compare(int& num1, int& num2) {
        string s1 = to_string(num1);
        string s2 = to_string(num2);
        if ((s1 + s2) < (s2 + s2)) return true;
        else return false;
    }
};

Another solution:
Data structure:
steps:
Complexity:
Runtime:
Space:
Code:

Things to learn:

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s