2610. Convert an Array Into a 2D Array With Conditions

Difficulty:
Related Topics:
Similar Questions:

    Problem

    You are given an integer array nums. You need to create a 2D array from nums satisfying the following conditions:

    Return the resulting array. If there are multiple answers, return any of them.

    Note that the 2D array can have a different number of elements on each row.

    Example 1:

    Input: nums = [1,3,4,1,2,3,1]
    Output: [[1,3,4,2],[1,3],[1]]
    Explanation: We can create a 2D array that contains the following rows:
    - 1,3,4,2
    - 1,3
    - 1
    All elements of nums were used, and each row of the 2D array contains distinct integers, so it is a valid answer.
    It can be shown that we cannot have less than 3 rows in a valid array.
    

    Example 2:

    Input: nums = [1,2,3,4]
    Output: [[4,3,2,1]]
    Explanation: All elements of the array are distinct, so we can keep all of them in the first row of the 2D array.
    

    Constraints:

    Solution (Java)

    import java.util.*;
    import java.lang.*;
    
    
    class Solution {
         Map<Integer,Integer> map=new HashMap<>();
        int ifany(Map<Integer,Integer> map)
        {
            for(int i:map.keySet())
            {
                if(map.get(i)>=1)
                    return 1;
            }
            return 0;
    
        }
    
    
        public List<List<Integer>> findMatrix(int[] nums) {
    
            List<Integer> temp=new ArrayList<>();
            List<List<Integer>> ans=new ArrayList<>();
    
            for(int i=0;i<nums.length;i++)
            {
                map.put(nums[i],1+map.getOrDefault(nums[i],0));
            }
            while(ifany(map)==1)
            {
            for(int i:map.keySet())
            {
                if(map.get(i)>=1)
                {
                    temp.add(i);
                    map.put(i,map.get(i)-1);
    
                }
            }
                ans.add(new ArrayList<>(temp));
                temp.clear();
            }
            return ans;
        }
    }
    

    Explain:

    nope.

    Complexity: