Get the App
SLTechnology News&Howtos  ›  Development  › 

How to understand the relative ordering of arrays by LeetCode

Shulou Source: shulou.com Published: 2022-06-02 18:25:28 10月05日 Update

This article introduces the relevant knowledge of "how to understand the relative ordering of arrays in LeetCode". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

Here are two arrays, arr1 and arr2

The elements in the arr2 are different

Every element in the arr2 appears in the arr1

Sort the elements in arr1 so that the relative order of items in arr1 is the same as the relative order in arr2. Elements that have not appeared in the arr2 need to be placed at the end of the arr1 in ascending order.

Example:

Input: arr1 = [2, 3, 4, 6, 7, 9, 2, 19], arr2 = [2, 1, 4, 4, 4, 6]

Output: [2, 2, 2, 1, 1, 4, 3, 3, 9, 9, 7, 19]

Tip:

Arr1.length, arr2.length 0) {

Res [index++] = I

Nums [I]-

}

}

/ / iterate through the nums to deal with the remaining elements that do not appear in the arr2

For (int I = 0; I

< nums.length; i++) {   while (nums[i]>

0) {

Res [index++] = I

Nums [I]-

}

}

Return res

}

3 、 python

Directly add arr2 plus arr1 and subtract the elements in arr2, and sort them from smallest to largest. Then sort the arr1 in the order of the subscripts in the arr2, and the rest in the original order.

Class Solution:

Def relativeSortArray (self, arr1: List [int], arr2: List [int])-> List [int]:

Arr2 + = sorted (set (arr1)-set (arr2))

Arr1.sort (key=arr2.index)

Return arr1

So much for the introduction of "how to understand the relative ordering of arrays in LeetCode". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Tags: Elements order sort array same number content quantity more knowledge processing statistics output practical from small to large learned and then subscript two since childhood Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno MySQL Linux Shulou Information NVidia Shulou Tech Info