|
| 1 | +// Approach 1 |
| 2 | +// Initialize an empty 2D list called list to store the sub-lists. |
| 3 | +// Initialize a variable count to keep track of the number of elements processed. |
| 4 | +// Use a while loop to iterate until all the elements in the nums array are processed. |
| 5 | +// Inside the loop, initialize a new sub-list ans to store unique integers from nums array. |
| 6 | +// For each element nums[i], if its not already present in the ans list, add it to ans, set nums[i] to zero (to mark it as processed), and increment count. |
| 7 | +// On reaching the end of nums array, add the ans list to the 2D list. |
| 8 | +// Continue this process until all elements of nums are processed. |
| 9 | + |
| 10 | + |
| 11 | +// class Solution { |
| 12 | +// public List<List<Integer>> findMatrix(int[] nums) { |
| 13 | +// List<List<Integer>> list=new ArrayList<>(); |
| 14 | +// int count=0; |
| 15 | +// while(count<nums.length){ |
| 16 | +// ArrayList<Integer> ans=new ArrayList<>(); |
| 17 | +// for(int i=0;i<nums.length;i++){ |
| 18 | +// if(nums[i]!=0 && !ans.contains(nums[i])){ |
| 19 | +// ans.add(nums[i]); |
| 20 | +// nums[i]=0; |
| 21 | +// count++; |
| 22 | +// } |
| 23 | +// } |
| 24 | +// list.add(ans); |
| 25 | +// } |
| 26 | +// return list; |
| 27 | +// } |
| 28 | +// } |
| 29 | + |
| 30 | + |
| 31 | +// This is a more optimized approach to achieve the same result. |
| 32 | +// Initialize an empty 2D list called list to store the sub-lists. |
| 33 | +// Initialize an integer array count of size nums.length + 1 to keep track of the count of each unique integer encountered in nums. |
| 34 | +// Iterate through each element i in the array nums. |
| 35 | +// Check if the count of the current integer i is equal to the size of the list. If it is, this implies that we have to add a new empty sub-list to list. |
| 36 | +// Add the current integer i to the appropriate sub-list in list, determined by its count stored in the count array. |
| 37 | +// Continue this process for all elements in the nums array. |
| 38 | +class Solution { |
| 39 | + public List<List<Integer>> findMatrix(int[] nums) { |
| 40 | + List<List<Integer>> list=new ArrayList<>(); |
| 41 | + int[] count=new int[nums.length+1]; |
| 42 | + for(int i:nums){ |
| 43 | + if(count[i]==list.size()){ |
| 44 | + list.add(new ArrayList<>()); |
| 45 | + } |
| 46 | + list.get(count[i]).add(i); |
| 47 | + count[i]++; |
| 48 | + } |
| 49 | + return list; |
| 50 | + } |
| 51 | +} |
0 commit comments