“This is the 18th day of my participation in the First Challenge 2022. For details: First Challenge 2022”

[B] [C] [D]

Given a set of non-negative integer nums, rearrange the order of each number (each number is not separable) to form the largest integer.

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

Example 1:

Input: nums = [10,2]Copy the code

Example 2:

Nums = [3,30,34,5,9] output: "9534330"Copy the code

Example 3:

Input: nums = [1]Copy the code

Example 4:

Nums = [10] Output: "10"Copy the code

Tip:

  • 1 <= nums.length <= 100
  • 0 <= nums[i] <= 109

Their thinking

In this case, we need to rearrange the order of the digits in the input so that the number after concatenation is the largest. So let’s just think about what’s the order when we only have two numbers? We can compare the result of a joining B with the result of B joining A. If the former is larger, a should be in front of B, and vice versa, B should be in front of A. With that in mind, we can use it as a sort rule and sort the input array using sort sort. After sorting the array, we can use the join method to get the string after joining the numbers. But we’re not done here, because there may be a [0,0] in the input data, and the converted string represents a number with a leading 0, and we need to deal with that. Here we can define a pointer to be initialized with the subscript 0. If the current character is 0, move it all the way back to the first non-0 position, and then intercept the rest. The important thing to note here is that the maximum value of l should be the string length minus 2, because we want to make sure that the result is a non-empty string.

Code implementation

Var largestNumber = function (nums) {var largestNumber = function (nums) {var largestNumber = function (nums) { Nums. sort((a, b) => (a + '+ b > b +' + a? 1: Const s = nums.join('') // because there is output data like [0,0], Let l = 0 // When the l pointer does not reach the last second of the string (this is because we want to ensure that the result is a non-empty string) // If the current character is 0, While (l < s.length-1&&s [l] === '0') l++ // return s.substr(l)}Copy the code

At this point we are done with leetcode-179- maximum number

If you have any questions or suggestions, please leave a comment! 👏 🏻 👏 🏻 👏 🏻