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

preface

This is the second question in the Weekly Contest 279. On Medium, it is a question about understanding and manipulating arrays.

describe

You are given an integer num. Rearrange the digits of num such that its value is minimized and it does not contain any leading zeros.

Return the rearranged number with minimal value.

Note that the sign of the number does not change after rearranging the digits.

Example 1:

Input: num = 310
Output: 103
Explanation: The possible arrangements for the digits of 310 are 013, 031, 103, 130, 301, 310. 
The arrangement with the smallest value that does not contain any leading zeros is 103.
Copy the code

Note:

  • -10^15 <= num <= 10^15

parsing

Give an integer num. Rearrange the number of num so that its value is minimized and does not contain any leading zeros. Returns the rearranged number with the minimum value. The important thing to note is that the numbers have pluses and minuses, and the pluses and minuses remain the same when you rearrange them.

If num is a positive number:

  • Put all the numbers in num into a list L and sort them in ascending order
  • Because it is a positive number, want to change after the minimum value, minimum value to make these Numbers can, but to prevent the first number is zero, so we need to traverse the elements in the L, from left to right to find out the first number is not zero, and then let the exchanged its elements and index 0, the elements in list L to merge into a string, Convert to an integer and return it

If num is negative:

  • Put all the numbers in num into a list L and sort them in descending order
  • Since it is a negative number, if you want to change the value to the minimum, you just need to make the value of these numbers to the maximum. And our L has been arranged in descending order, so we can directly merge the elements in L, convert them into negative integers and return them

Time is O(N), space is O(N). Of course, this code is definitely redundant, but it can be simplified to less than ten lines of code.

answer

Class Solution(object): def smallestNumber(self, num): "" :type num: int :rtype: int "" Sorted (list(STR (num)[1:]), reverse=True) return -int(".join(L)) # 0, leave unchanged elif num == 0: Else: L = sorted(list(STR (num))) idx = 0 while idx<len(L): if L[idx]! ='0': break idx += 1 L[idx], L[0] = L[0], L[idx] return int(''.join(L))Copy the code

The results

413/413 Test cases passed. Status: Accepted Runtime: 18 MS Memory Usage: 13.2 MBCopy the code

The original link

Leetcode.com/contest/wee…

Your support is my biggest motivation