14.Largest Number

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

Example 1:
Input: nums = [10,2]
Output: "210"

Example 2:
Input: nums = [3,30,34,5,9]
Output: "9534330"

Example 3:
Input: nums = [1]
Output: "1"

Example 4:
Input: nums = [10]
Output: "10"

Solution I:

Approach: Sorting with a compare.

class Solution
{
public:
    string largestNumber(vector<int> &nums)
    {

        for (int i = 0; i < nums.size(); i++)
        {
            for (int j = i + 1; j < nums.size(); j++)
            {
                string a = to_string(nums[i]) + to_string(nums[j]);
                string b = to_string(nums[j]) + to_string(nums[i]);

                if (b > a)
                {
                    swap(nums[i], nums[j]);
                }
            }
        }

        if (nums[0] == 0)
        {
            return "0";
        }
        
        string res = "";
        for (int i = 0; i < nums.size(); i++)
        {
            res = res + to_string(nums[i]);
        }

        return res;
    }
};

Time Complexity: O(N^2)

Solution II:

Time Complexity: O(N log n), Space Complexity: O(N)

Last updated

Was this helpful?