Re: [閒聊] 每日leetcode已回收
1122. Relative Sort Array
給定兩個陣列 arr1 和 arr2,arr2 的元素是不同的,而且 arr2 中的所有元素也都在 arr1 中。
對 arr1 的元素進行排序,使得 arr1 中的項目相對順序與 arr2 相同。不在 arr2 中出現的元素應該按升序放在 arr1 的末尾。
Example 1:
Input: arr1 = [2,3,1,3,2,4,6,7,9,2,19], arr2 = [2,1,4,3,9,6]
Output: [2,2,2,1,4,3,3,9,6,7,19]
思路:寫個comparer就好
C# code:
public class Solution
{
public int[] RelativeSortArray(int[] arr1, int[] arr2)
{
var dict = new Dictionary<int, int>();
for (int i = 0; i < arr2.Length; i++)
{
dict[arr2[i]] = i;
}
Array.Sort(arr1, Comparer<int>.Create((a, b) =>
{
bool finda = dict.TryGetValue(a, out int ia);
bool findb = dict.TryGetValue(b, out int ib);
if (finda && findb) return ia.CompareTo(ib);
if (finda && !findb) return -1;
if (!finda && findb) return 1;
return a.CompareTo(b);
}));
return arr1;
}
}
--
(づ′・ω・)づ
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 61.220.51.52 (臺灣)
※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1718077139.A.DB2.html
推
06/11 11:41,
1年前
, 1F
06/11 11:41, 1F
推
06/11 11:41,
1年前
, 2F
06/11 11:41, 2F
→
06/11 11:41,
1年前
, 3F
06/11 11:41, 3F
推
06/11 11:43,
1年前
, 4F
06/11 11:43, 4F
推
06/11 11:44,
1年前
, 5F
06/11 11:44, 5F
推
06/11 12:44,
1年前
, 6F
06/11 12:44, 6F
討論串 (同標題文章)
完整討論串 (本文為第 341 之 1548 篇):