Re: [閒聊] 每日LeetCode
看板Marginalman作者JerryChungYC (JerryChung)時間5月前 (2024/01/02 20:21)推噓0(0推 0噓 0→)留言0則, 0人參與討論串592/719 (看更多)
早上有解不過翻中文太難了
Python3 Code:
-------------------------------------
class Solution:
def findMatrix(self, nums: List[int]) -> List[List[int]]:
if len(set(nums)) == len(nums):
return [nums]
res = []
for num in range(len(nums)):
cnt = nums[:num+1].count(nums[num])
if len(res) < cnt:
res.append([])
res[cnt-1].append(nums[num])
return res
原本有用dict 不過後來改直接用count 但數據還是一樣爛就是了 :(
※ 引述《Rushia (みけねこ的鼻屎)》之銘言:
: https://leetcode.com/problems/convert-an-array-into-a-2d-array-with-conditions/description
: 2610. Convert an Array Into a 2D Array With Conditions
: 給你一個整數陣列 nums[],我們要把他轉換成一個矩陣,這個矩陣的每一列元素都不相
: 同且列數需盡可能小。
: 1.用一個陣列紀錄每個元素下一次加入矩陣時要加到第幾列,從第0列開始放,每次遞增
: ,如果列數超過List大小時就擴容。
: Java Code:
: -------------------------------------
: class Solution {
: public List<List<Integer>> findMatrix(int[] nums) {
: int[] next = new int[nums.length + 1];
: ArrayList<List<Integer>> res = new ArrayList<>();
: for (int num : nums) {
: if (next[num] == res.size()) {
: res.add(new ArrayList<>());
: }
: res.get(next[num]).add(num);
: next[num]++;
: }
: return res;
: }
: }
: -------------------------------------
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 114.45.21.7 (臺灣)
※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1704198090.A.635.html
討論串 (同標題文章)