Write the directory title here
1. The product of numbers other than itself
Given you an integer array nums, return the array answer , where answer[i] is equal to the product of the remaining elements in nums except nums[i].
The question data ensures that the product of all prefix elements and suffixes of any element in the array nums is within the range of 32-bit integers.
Please do not use division and complete this problem in O(n) time complexity.
Example 1:
Input: nums = [1,2,3,4]
Output: [24,12,8,6]
Example 2:
Import: nums = [-1,1,0,-3,3]
Export: [0,0, 9,0,0]
def test2(nums):
n = len(nums)
res = [0] * n
k = 1
for i in range(n):
res[i] = k
k = k * nums[i]
k = 1
for i in range(n - 1, -1, -1):
res[i] = k * res[i]
k = k * nums[i]
return res
nums = [1, 2, 3, 4]
res = test2(nums)
print(res)
2. Maximum number
Given a list consisting of some non-negative integers, rearrange their order to form the largest integer.
Example:
Input:
[30,1]
Return value: a>
“301”
import itertools
nums = [1, 201, 20, 9, 8]
s = list(map(str, nums))
print(s)
ordered = sorted(s, key=lambda x: x, reverse=True)
print(ordered)
def fn(nums):
s = list(map(str, nums)) # [30,1] ——》 ['30', '1']
ordered = sorted(s, key=lambda x: x, reverse=True) # 根据首位排序
# 首位相同的,进行二次排序
for i in range(len(ordered) - 1):
if ordered[i][0] == ordered[i + 1][0]:
if int(ordered[i][-1]) < int(ordered[i + 1][-1]):
ordered[i], ordered[i + 1] = ordered[i + 1], ordered[i]
return int(''.join(ordered))
nums = [301, 302, 34]
print(fn(nums))
3. Odd sorting
Harry Potter is given a list of numbers and his task is that he must sort the odd numbers in ascending order while leaving the even numbers in their original positions. Magicians, come and help him~
nums = [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
def test(nums):
res1 = sorted([i for i in nums if i % 2 == 1])
for index in range(len(nums)):
if nums[index] % 2 != 0:
nums[index] = res1[0]
res1.pop(0)
return nums
r = test(nums)
print(r)