For sparse venctors, there might be too many "0"s in the array. What we need to do is only abstract the items which are not "0". We store these non-zero items in HashMap or HashSet.

The HashMap solution is as following:

class SparseVector {
    Map<Integer, Integer> map = new HashMap<>();
    SparseVector(int[] nums) {
        for(int i=0;i<nums.length;i++){
            if(nums[i]!=0){
                map.put(i, nums[i]);
            }
        }
    }
    
    // Return the dotProduct of two sparse vectors
    public int dotProduct(SparseVector vec) {
        Map<Integer, Integer> map1 = this.map;
        Map<Integer, Integer> map2 = vec.map;
        if(map1.size()>map2.size()){   //this is for follow up question
            return vec.dotProduct(this);
        }
        int sum = 0;
        for(Integer key: map1.keySet()){
            if(map2.containsKey(key)){
                sum+=map1.get(key)*map2.get(key);
            }
        }
        return sum;
    }
}

For follow up question: What if only one of the vectors is sparse? 

The answer is, we compare the two HashMaps, we iterate the HashMap which has a smaller size.

We can also use HashSet to store the index of the nums, and get value from nums.

class SparseVector {
    Set<Integer> set = new HashSet<>();
    int[] nums;
    SparseVector(int[] nums) {
        this.nums = nums;
        for(int i=0;i<nums.length;i++){
            if(nums[i]!=0){
                set.add(i);
            }
        }
    }
    
    // Return the dotProduct of two sparse vectors
    public int dotProduct(SparseVector vec) {
        Set<Integer> set1 = this.set;
        Set<Integer> set2 = vec.set;
        if(set1.size()>set2.size()){   //this is for follow up question
            return vec.dotProduct(this);
        }
        int sum = 0;
        for(Integer i: set1){
            if(set2.contains(i)){
                sum+=nums[i]*vec.nums[i];
            }
        }
        return sum;
    }
}

 

posted on 2022-02-08 04:13  阳光明媚的菲越  阅读(28)  评论(0编辑  收藏  举报