【Leetcode 每日一题】2176. 统计数组中相等且可以被整除的数对

问题背景

给你一个下标从 0 0 0 开始长度为 n n n 的整数数组 n u m s nums nums 和一个整数 k k k,请你返回满足 0 ≤ i < j < n 0 \le i < j < n 0≤i<j<n, n u m s [ i ] = n u m s [ j ] nums[i] = nums[j] nums[i]=nums[j] 且 ( i × j ) (i \times j) (i×j) 能被 k k k 整除的数对 ( i , j ) (i, j) (i,j) 的 数目

数据约束

  • 1 ≤ n u m s . l e n g t h ≤ 100 1 \le nums.length \le 100 1≤nums.length≤100
  • 1 ≤ n u m s [ i ] , k ≤ 100 1 \le nums[i], k \le 100 1≤nums[i],k≤100

解题过程

这题数据范围不大,暴力枚举也能过。

一种更好的做法,是将值像等的元素都保存在链表中,遍历时就只需要判断能否整除了。

具体实现

java 复制代码
class Solution {
    public int countPairs(int[] nums, int k) {
        int n = nums.length;
        int res = 0;
        ListNode[] map = new ListNode[110];
        for (int i = 0; i < n; i++) {
            ListNode cur = new ListNode(i);
            ListNode pre = map[nums[i]];
            if (pre != null) {
                cur.next = pre;
            }
            while (pre != null) {
                if (i * pre.index % k == 0) {
                    res++;
                }
                pre = pre.next;
            }
            map[nums[i]] = cur;
        }
        return res;
    }
}

class ListNode {
    int index;
    ListNode next;
    ListNode(int index) {
        this.index = index;
        next = null;
    }
}
相关推荐
程序员清洒7 分钟前
CANN模型剪枝:从敏感度感知到硬件稀疏加速的全链路压缩实战
算法·机器学习·剪枝
vortex521 分钟前
几种 dump hash 方式对比分析
算法·哈希算法
堕27436 分钟前
java数据结构当中的《排序》(一 )
java·数据结构·排序算法
2302_813806221 小时前
【嵌入式修炼:数据结构篇】——数据结构总结
数据结构
Wei&Yan1 小时前
数据结构——顺序表(静/动态代码实现)
数据结构·c++·算法·visual studio code
团子的二进制世界2 小时前
G1垃圾收集器是如何工作的?
java·jvm·算法
吃杠碰小鸡2 小时前
高中数学-数列-导数证明
前端·数学·算法
故事不长丨2 小时前
C#线程同步:lock、Monitor、Mutex原理+用法+实战全解析
开发语言·算法·c#
long3162 小时前
Aho-Corasick 模式搜索算法
java·数据结构·spring boot·后端·算法·排序算法
近津薪荼2 小时前
dfs专题4——二叉树的深搜(验证二叉搜索树)
c++·学习·算法·深度优先