【算法】1282. 用户分组(多语言实现)

273 阅读3分钟

携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第14天,点击查看活动详情


1282. 用户分组:

n 个人被分成数量未知的组。每个人都被标记为一个从 0n - 1唯一ID

给定一个整数数组 groupSizes ,其中 groupSizes[i] 是第 i 个人所在的组的大小。例如,如果 groupSizes[1] = 3 ,则第 1 个人必须位于大小为 3 的组中。

返回一个组列表,使每个人 i 都在一个大小为 groupSizes[i] 的组中。

每个人应该 恰好只 出现在 一个组 中,并且每个人必须在一个组中。如果有多个答案,返回其中 任何 一个。可以 保证 给定输入 至少有一个 有效的解。

样例 1:

输入:
	groupSizes = [3,3,3,3,3,1,3]
	
输出:
	[[5],[0,1,2],[3,4,6]]
	
解释:
	第一组是 [5],大小为 1,groupSizes[5] = 1。
	第二组是 [0,1,2],大小为 3,groupSizes[0] = groupSizes[1] = groupSizes[2] = 3。
	第三组是 [3,4,6],大小为 3,groupSizes[3] = groupSizes[4] = groupSizes[6] = 3。 
	其他可能的解决方案有 [[2,1,6],[5],[0,4,3]][[5],[0,6,2],[4,3,1]]

样例 2:

输入:
	groupSizes = [2,1,3,3,3,2]
	
输出:
	[[1],[0,5],[2,3,4]]

提示:

  • groupSizes.length == n
  • 1 <= n <= 500
  • 1 <= groupSizes[i] <= n

分析

  • 面对这道算法题目,二当家的陷入了沉思。
  • 题目并没有要求寻找所有可能性。
  • 题目说一定有解,那么按照数字分组计数,每个数字的个数一定是该数字的整倍数,这时候再分组,就按顺序分配就可以。所以可以遍历数字,以数字为key,以唯一ID(也就是数组下标)为value,最后按顺序放入分组结果就可以。
  • 思考现实中的分组,比如团购,我们只要够成团的人数,这一组就交易达成了,后面人的就是后面的事情了。

题解

rust

impl Solution {
    pub fn group_the_people(group_sizes: Vec<i32>) -> Vec<Vec<i32>> {
        let mut ans = Vec::new();

        let mut grouper: Vec<Vec<i32>> = vec![Vec::new(); group_sizes.len() + 1];
        group_sizes.iter().enumerate().for_each(|(i, &groupSize)| {
            if groupSize == 1 {
                // 一人一组的注定孤独,没必要麻烦别人,自己玩吧
                ans.push(vec![i as i32]);
            } else {
                grouper[groupSize as usize].push(i as i32);
                if grouper[groupSize as usize].len() == groupSize as usize {
                    // 凑齐一组,离开计数器
                    ans.push(grouper[groupSize as usize].clone());
                    grouper[groupSize as usize].clear();
                }
            }
        });

        ans
    }
}

go

func groupThePeople(groupSizes []int) [][]int {
    var ans [][]int

    grouper := make([][]int, len(groupSizes) + 1)
    for i, groupSize := range groupSizes {
        if groupSize == 1 {
            // 一人一组的注定孤独,没必要麻烦别人,自己玩吧
            ans = append(ans, []int{i})
        } else {
            grouper[groupSize] = append(grouper[groupSize], i)
            if len(grouper[groupSize]) == groupSize {
                // 凑齐一组,离开计数器
                ans = append(ans, grouper[groupSize])
                grouper[groupSize] = []int{}
            }
        }
    }

    return ans
}

typescript

function groupThePeople(groupSizes: number[]): number[][] {
    const ans = [];
    const grouper = [];
    for (const i in groupSizes) {
        const groupSize = groupSizes[i];
        if (groupSize == 1) {
            // 一人一组的注定孤独,没必要麻烦别人,自己玩吧
            ans.push([i]);
        } else {
            if (!grouper[groupSize]) {
                grouper[groupSize] = [];
            }
            grouper[groupSize].push(i)
            if (grouper[groupSize].length == groupSize) {
                // 凑齐一组,离开计数器
                ans.push(grouper[groupSize]);
                grouper[groupSize] = [];
            }
        }
    }
    return ans;
};

c

/**
 * Return an array of arrays of size *returnSize.
 * The sizes of the arrays are returned as *returnColumnSizes array.
 * Note: Both returned array and *columnSizes array must be malloced, assume caller calls free().
 */
int** groupThePeople(int* groupSizes, int groupSizesSize, int* returnSize, int** returnColumnSizes){
    int **ans = (int **) malloc(groupSizesSize * sizeof(int *));
    *returnColumnSizes = (int *) malloc(groupSizesSize * sizeof(int));
    *returnSize = 0;

    // 待分组的伙伴需要一个等待室
    int grouper[groupSizesSize + 1][groupSizesSize];
    int grouperSize[groupSizesSize + 1];
    memset(grouperSize, 0, (groupSizesSize + 1) * sizeof (int));
    for (int i = 0; i < groupSizesSize; ++i) {
        int groupSize = groupSizes[i];
        if (groupSize == 1) {
            // 一人一组的注定孤独,没必要麻烦别人,自己玩吧
            ans[*returnSize] = (int*) malloc(sizeof(int));
            ans[*returnSize][0] = i;
            (*returnColumnSizes)[(*returnSize)++] = 1;
        } else {
            grouper[groupSize][grouperSize[groupSize]++] = i;
            if (grouperSize[groupSize] == groupSize) {
                // 凑齐一组,离开等待室
                ans[*returnSize] = (int*) malloc(groupSize * sizeof(int));
                memcpy(ans[*returnSize], grouper[groupSize], groupSize * sizeof (int));
                (*returnColumnSizes)[(*returnSize)++] = groupSize;
                grouperSize[groupSize] = 0;
            }
        }
    }

    return ans;
}    

c++

class Solution {
public:
    vector<vector<int>> groupThePeople(vector<int>& groupSizes) {
        vector<vector<int>> ans;

        // 待分组的伙伴需要一个等待室
        vector<int> grouper[groupSizes.size() + 1];
        for (int i = 0; i < groupSizes.size(); ++i) {
            int groupSize = groupSizes[i];
            if (groupSize == 1) {
                // 一人一组的注定孤独,没必要麻烦别人,自己玩吧
                vector<int> g;
                g.emplace_back(i);
                ans.emplace_back(g);
            } else {
                grouper[groupSize].emplace_back(i);
                if (grouper[groupSize].size() == groupSize) {
                    // 凑齐一组,离开等待室
                    ans.emplace_back(grouper[groupSize]);
                    grouper[groupSize].clear();
                }
            }
        }

        return ans;
    }
};

java

class Solution {
    public List<List<Integer>> groupThePeople(int[] groupSizes) {
        List<List<Integer>> ans = new ArrayList<>();

        // 待分组的伙伴需要一个等待室
        List<Integer>[] grouper = new List[groupSizes.length + 1];
        for (int i = 0; i < groupSizes.length; ++i) {
            int groupSize = groupSizes[i];
            if (groupSize == 1) {
                // 一人一组的注定孤独,没必要麻烦别人,自己玩吧
                List<Integer> g = new ArrayList<>();
                g.add(i);
                ans.add(g);
            } else {
                if (grouper[groupSize] == null) {
                    grouper[groupSize] = new ArrayList<>();
                }
                grouper[groupSize].add(i);
                if (grouper[groupSize].size() == groupSize) {
                    // 凑齐一组,离开等待室
                    ans.add(grouper[groupSize]);
                    grouper[groupSize] = null;
                }
            }
        }

        return ans;
    }
}

python

class Solution:
    def groupThePeople(self, groupSizes: List[int]) -> List[List[int]]:
        ans = []
        grouper = [[] for i in range(len(groupSizes) + 1)]
        for i, groupSize in enumerate(groupSizes):
            if groupSize == 1:
                # 一人一组的注定孤独,没必要麻烦别人,自己玩吧
                ans.append([i])
            else:
                grouper[groupSize].append(i)
                if len(grouper[groupSize]) == groupSize:
                    # 凑齐一组,离开计数器
                    ans.append(grouper[groupSize])
                    grouper[groupSize] = []
        return ans
        

原题传送门:https://leetcode.cn/problems/group-the-people-given-the-group-size-they-belong-to/


非常感谢你阅读本文~
放弃不难,但坚持一定很酷~
希望我们大家都能每天进步一点点~
本文由 二当家的白帽子:https://juejin.cn/user/2771185768884824/posts 博客原创~