Optimized solution


  • 0
    G

    '''
    public class Solution {
    public int[][] multiply(int[][] A, int[][] B) {

        // Initializing map row-wise
        Map<Integer, Map<Integer, Integer>> a = new HashMap<>();
        for(int i=0;i<A.length;i++){
            Map<Integer, Integer> map = new HashMap<>();
            for(int j=0;j<A[0].length;j++){
                if(A[i][j] != 0){
                    map.put(j, A[i][j]);
                }
            }
            // Not storing rows which have no data
            if(map.size() !=0) a.put(i, map);
        }
        
        // Initializing map column-wise
        Map<Integer, Map<Integer, Integer>> b = new HashMap<>();
        for(int j=0;j<B[0].length;j++){
            Map<Integer, Integer> map = new HashMap<>();
            for(int i=0;i<B.length;i++){
                if(B[i][j] != 0){
                    map.put(i, B[i][j]);
                }
            }
            // Not storing columns which have no data
            if(map.size() !=0) b.put(j, map);
        }
        
        //Initializing result with correct size
        int[][] result = new int[A.length][B[0].length];
        
        for(Map.Entry<Integer, Map<Integer, Integer>> aEntry : a.entrySet()){
            // This map is initialized row-wise. So the key will give us the correct row
            int row = aEntry.getKey();
            
            // Looping through every column which has atleast one data point
            for(Map.Entry<Integer, Map<Integer, Integer>> bEntry : b.entrySet()){
                
                // Since this map is arranged column wise, key will give us column
                int column = bEntry.getKey();
                int value = 0;
                
                // Looping through all the values in the row
                for(Map.Entry<Integer, Integer> aEntryValues : aEntry.getValue().entrySet()){
                    
                    int location = aEntryValues.getKey();
                    // Adding only if a corresponding value exists in matrix b
                    if(bEntry.getValue().containsKey(location)){
                        value += aEntryValues.getValue()*bEntry.getValue().get(location);
                    }
                }
                // Setting value
                result[row][column] = value;
            }
            
        }
        return result;
    }
    

    }
    '''


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.