LeetCode 题解工作台

对角线上的质数

给你一个下标从 0 开始的二维整数数组 nums 。 返回位于 nums 至少一条 对角线 上的最大 质数 。如果任一对角线上均不存在质数,返回 0 。 注意: 如果某个整数大于 1 ,且不存在除 1 和自身之外的正整数因子,则认为该整数是一个质数。 如果存在整数 i ,使得 nums[i][i] …

category

4

题型

code_blocks

7

代码语言

hub

3

相关题

当前训练重点

简单 · 数组·数学

bolt

答案摘要

我们实现一个函数 `is_prime`,判断一个数是否为质数。 然后遍历数组,判断对角线上的数是否为质数,如果是,更新答案。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数组·数学 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个下标从 0 开始的二维整数数组 nums

返回位于 nums 至少一条 对角线 上的最大 质数 。如果任一对角线上均不存在质数,返回 0 。

注意:

  • 如果某个整数大于 1 ,且不存在除 1 和自身之外的正整数因子,则认为该整数是一个质数。
  • 如果存在整数 i ,使得 nums[i][i] = val 或者 nums[i][nums.length - i - 1]= val ,则认为整数 val 位于 nums 的一条对角线上。

在上图中,一条对角线是 [1,5,9] ,而另一条对角线是 [3,5,7]

 

示例 1:

输入:nums = [[1,2,3],[5,6,7],[9,10,11]]
输出:11
解释:数字 1、3、6、9 和 11 是所有 "位于至少一条对角线上" 的数字。由于 11 是最大的质数,故返回 11 。

示例 2:

输入:nums = [[1,2,3],[5,17,7],[9,11,10]]
输出:17
解释:数字 1、3、9、10 和 17 是所有满足"位于至少一条对角线上"的数字。由于 17 是最大的质数,故返回 17 。

 

提示:

  • 1 <= nums.length <= 300
  • nums.length == numsi.length
  • 1 <= nums[i][j] <= 4*106
lightbulb

解题思路

方法一:数学 + 模拟

我们实现一个函数 is_prime,判断一个数是否为质数。

然后遍历数组,判断对角线上的数是否为质数,如果是,更新答案。

时间复杂度 O(n×M)O(n \times \sqrt{M}),其中 nnMM 分别为数组的行数和数组中的最大值。空间复杂度 O(1)O(1)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution:
    def diagonalPrime(self, nums: List[List[int]]) -> int:
        def is_prime(x: int) -> bool:
            if x < 2:
                return False
            return all(x % i for i in range(2, int(sqrt(x)) + 1))

        n = len(nums)
        ans = 0
        for i, row in enumerate(nums):
            if is_prime(row[i]):
                ans = max(ans, row[i])
            if is_prime(row[n - i - 1]):
                ans = max(ans, row[n - i - 1])
        return ans
speed

复杂度分析

指标
时间complexity is O(n * sqrt(m)) where n is the matrix size and m is the maximum element, due to checking primality for each diagonal element. Space complexity is O(n) for storing diagonal numbers temporarily.
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Expect candidates to iterate only over diagonals rather than the full matrix.

  • question_mark

    Look for optimized primality checks rather than naive looping over all numbers.

  • question_mark

    Notice if candidates handle the edge case where no prime exists.

warning

常见陷阱

外企场景
  • error

    Iterating over the entire matrix instead of just the diagonals wastes time.

  • error

    Checking primality inefficiently can lead to timeouts for large numbers.

  • error

    Failing to return 0 when no prime exists on the diagonals.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Find the smallest prime on any diagonal instead of the largest.

  • arrow_right_alt

    Sum all prime numbers on the diagonals rather than returning the maximum.

  • arrow_right_alt

    Check only the main diagonal for primes and ignore the anti-diagonal.

help

常见问题

外企场景

对角线上的质数题解:数组·数学 | LeetCode #2614 简单