[코테 풀이] Merge Similar Items

시내·2024년 6월 28일

Q_2363) Merge Similar Items

출처 : https://leetcode.com/problems/merge-similar-items/

You are given two 2D integer arrays, items1 and items2, representing two sets of items. Each array items has the following properties:

  • items[i] = [valuei, weighti] where valuei represents the value and weighti represents the weight of the ith item.

  • The value of each item in items is unique.

Return a 2D integer array ret where ret[i] = [valuei, weighti], with weighti being the sum of weights of all items with value valuei.

Note: ret should be returned in ascending order by value.

class Solution {
     public  class Compare implements Comparator<List<Integer>> {
        @Override
        public int compare(List<Integer> o1, List<Integer> o2) {
            return o1.get(0) - o2.get(0);
        }
     }
         
    public List<List<Integer>> mergeSimilarItems(int[][] items1, int[][] items2) {
            List<List<Integer>> arr = new ArrayList<>();
            boolean[] n1 = new boolean[items1.length];
            boolean[] n2 = new boolean[items2.length];
            for (int i = 0; i < items1.length; i++) {
                for (int j = 0; j < items2.length; j++) {
                    List<Integer> sub = new ArrayList<>();
                    if (items1[i][0] == items2[j][0]) {
                        sub.add(items1[i][0]);
                        sub.add(items1[i][1] + items2[j][1]);
                        n1[i] = true;
                        n2[j] = true;
                    }
                    if (sub.size() > 0) arr.add(new ArrayList<>(sub));
                }
            }
            for (int a = 0; a < n1.length; a++) {
                if (!n1[a]) arr.add(new ArrayList<>(Arrays.asList(items1[a][0], items1[a][1])));
            }
            for (int b = 0; b < n2.length; b++) {
                if (!n2[b]) arr.add(new ArrayList<>(Arrays.asList(items2[b][0], items2[b][1])));
            }
            arr.sort(new Compare());
            return arr;
        }
     }
profile
contact 📨 ksw08215@gmail.com

0개의 댓글