每日打卡

2021-11-27 011 前缀和

2021-11-27  本文已影响0人  16孙一凡通工

前缀和的定义就是从location i 到location j 的和,
常见的就是对于某个长度n的序列,进行m次查询,查询当中统计location i 到location j 的和
011里面采用哈希表加前缀和的思路,遍历数组,每次用count统计1,0的个数差,每次统计过程中,采用哈希表,key是count,value是location,每次遍历,当前count在哈希表内已经存在,就更新哈希表的value,这个value就是当前location减去上一次count出现的location。

java版本

class Solution {
    public int findMaxLength(int[] nums) {

        HashMap<Integer,Integer> hashmap=new HashMap<>();

        hashmap.put(0,-1);
        int count=0,res=0;
        for(int i=0;i<nums.length;i++){
       if(nums[i]==0){
           count-=1;
       }else{
           count+=1;
       }
       if(hashmap.containsKey(count)){
           res=Math.max(res,i-hashmap.get(count));
       }else{
           hashmap.put(count,i);
       }

        }
        return res;
    }
}

Go版本

func findMaxLength(nums []int) int {

    // 前缀和

    hashmap:=make(map[int]int);

    count,res:=0,0;
    hashmap[0]=-1;
    for key,value :=range nums{
        if value==0{
            count-=1;
        }else{
            count+=1;
        }
        loc,ok:=hashmap[count];
        if ok{
          res=max(res,key-loc);
        }else{
            hashmap[count]=key;
        }
       
    }
    return res;

}
func max(num1 int,num2 int)int{
    if num1>num2{
        return num1;
    }
    return num2;
}
上一篇 下一篇

猜你喜欢

热点阅读