Re: [閒聊] 每日leetcode

看板Marginalman作者 (早瀬ユウカの体操服 )時間9月前 (2025/03/03 23:18), 編輯推噓1(101)
留言2則, 2人參與, 9月前最新討論串1357/1552 (看更多)
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
有可能直接用原本的nums做出來嗎
03/04 16:17, 1F

03/04 21:27, 9月前 , 2F
不知道ㄟ沒看解答
03/04 21:27, 2F
文章代碼(AID): #1dnSXVxC (Marginalman)
討論串 (同標題文章)
文章代碼(AID): #1dnSXVxC (Marginalman)