【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 numsi = numsj numsi=numsj 且 ( 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 numsi, k \le 100 1≤numsi,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;
    }
}
相关推荐
圣保罗的大教堂22 分钟前
leetcode 301. 删除无效的括号 困难
leetcode
liliangcsdn36 分钟前
派息率指标的应用探索和分析
大数据·算法
垆边人似月.1 小时前
华为机试题 :两数之和
c++·算法·华为
默默开发1 小时前
物流行业可用算法方向
算法
垆边人似月.1 小时前
华为机试题 :有效的括号
c++·算法·华为
A加ITIL教练长河achotsao2 小时前
ITIL Master 战略领导者课后系列分享:AI编程正在重新划分研发与运维的边界
算法
hahaha60162 小时前
FPGA+ARM实现AWB的全流程
人工智能·嵌入式硬件·算法·计算机视觉·fpga开发
李洱2 小时前
LangChain 和 LangGraph 的区别:核心原理与使用场景
算法
夏幻灵2 小时前
每日一题:LeetCode 206:反转链表——三指针与原地反转详解
算法·leetcode·链表