Re: [閒聊] 每日LeetCode
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), 來自: 122.100.73.13 (臺灣)
※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1704188939.A.D77.html
推
01/02 18:14,
1年前
, 1F
01/02 18:14, 1F
討論串 (同標題文章)
完整討論串 (本文為第 591 之 719 篇):