C/C++教程

1570. Dot Product of Two Sparse Vectors

本文主要是介绍1570. Dot Product of Two Sparse Vectors,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

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;
    }
}

 

这篇关于1570. Dot Product of Two Sparse Vectors的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!