P4009.和为K的子数组个数 & P5522.异或和为 k 的子数组个数

题目

https://codefun2000.com/ide/P4009?pset=zijie

https://codefun2000.com/ide/P5522?pset=zijie

思路

code(ACM)

java 复制代码
import java.util.*;
class Main{
    public static void main(String args[]){
        Scanner sc=new Scanner(System.in);
        long n=sc.nextLong();
        long k=sc.nextLong();
        long arr[]=new long [(int)n];
        for (int i = 0; i < n; i++) {
            arr[i]=sc.nextLong();
        }

        long sum=0;
        long pre[]=new long[(int)n+1];//从1开始计数
        HashMap<Long,Long> map=new HashMap<>();
        map.put(0L,1L);
        for(int i=0;i<n;i++){
            pre[i+1]=pre[i]+arr[i];
            sum= sum + map.getOrDefault(pre[i+1]-k,0L);//查找 pre[i+1]-k 出现了多少次。
            map.put(pre[i+1], map.getOrDefault(pre[i+1],0L)+1L);//记录当前前缀和 pre[i+1] 出现了多少次。

        }
        System.out.print(sum);
    }
}
java 复制代码
import java.util.*;

class Main {
    public static void main(String args[]) {
        Scanner sc = new Scanner(System.in);

        long n = sc.nextLong();
        long k = sc.nextLong();

        long arr[] = new long[(int)n];
        for (int i = 0; i < n; i++) {
            arr[i] = sc.nextLong();
        }

        long sum = 0;
        long pre[] = new long[(int)n + 1]; // 从1开始计数

        HashMap<Long, Long> map = new HashMap<>();
        map.put(0L, 1L);

        for (int i = 0; i < n; i++) {
            pre[i + 1] = pre[i] ^ arr[i];
            sum = sum + map.getOrDefault(pre[i + 1] ^ k, 0L);
            map.put(pre[i + 1],
                    map.getOrDefault(pre[i + 1], 0L) + 1L);
        }

        System.out.print(sum);
    }
}
相关推荐
TinyKey1 小时前
malloc_debug_notes
java
郭小李1 小时前
spring @PathVariable 注解用法
java·后端·spring
用户3126874877201 小时前
Java 锁全景:synchronized、ReentrantLock、ReadWriteLock、StampedLock
java
鱼宵1 小时前
CSV 怎么做销售报表?Stream 第 9 课:读洗聚排打五段管道一次跑通
java·报表·stream
jaysee-sjc1 小时前
【苍穹外卖】Day12:工作台数据看板与 Excel 报表导出
java·开发语言·数据库·spring boot·spring·微信·excel
w_zero_one1 小时前
算法--桶思想
java·开发语言·算法
MetaLite1 小时前
Spring 同一个类里调用 @CacheEvict,为什么缓存没清掉?
java·spring·缓存
一个游离的指针2 小时前
ES6新特性:let、const、块级作用域
开发语言·javascript·es6
sunburn-2 小时前
数据库聚合查询完整教程:从基础函数到实战统计
java·数据库·mysql·数据库开发