Re: [閒聊] 每日leetcode
https://leetcode.com/problems/partition-array-according-to-given-pivot
2161. Partition Array According to Given Pivot
給你一個陣列nums和一個數字pivot,小於pivot的數字要在所有pivot左邊,反之要在
右邊,除了pivot以外的數字必須保持原陣列的相對位置。
思路:
1.遍歷一次找出所有比較小的數字照順序放入陣列,順便統計有幾個pivot。
2.放入cnt個pivot。
3.把剩下比pivot大的數字照順序放入陣列。
Java Code:
--------------------------------------------
class Solution {
public int[] pivotArray(int[] nums, int pivot) {
int[] res = new int[nums.length];
int k = 0;
int cnt = 0;
for (int num : nums) {
if (num == pivot) {
cnt++;
} else if (num < pivot) {
res[k++] = num;
}
}
for (int i = 0; i < cnt; i++) {
res[k++] = pivot;
}
for (int num : nums) {
if (num > pivot) {
res[k++] = num;
}
}
return res;
}
}
--------------------------------------------
--
https://i.imgur.com/SLF19AR.jpeg

--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 49.158.101.161 (臺灣)
※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1741015135.A.ECC.html
推
03/04 16:17,
9月前
, 1F
03/04 16:17, 1F
→
03/04 21:27,
9月前
, 2F
03/04 21:27, 2F
討論串 (同標題文章)
完整討論串 (本文為第 1357 之 1552 篇):