Skip to content

74. 搜索二维矩阵

74. 搜索二维矩阵

代码

javascript
// 74. 搜索二维矩阵:https://leetcode.cn/problems/search-a-2d-matrix/
// 输入:matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3
// 输出:true

export function searchA_2dMatrix (matrix, target) {
  return matrix.flat().includes(target)
}
typescript
// 74. 搜索二维矩阵:https://leetcode.cn/problems/search-a-2d-matrix/
// 输入:matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3
// 输出:true

export function searchA_2dMatrix (matrix: number[][], target: number): boolean {
  return matrix.flat().includes(target)
}

测试代码

ts
import { expect, test } from 'vitest'
import { searchA_2dMatrix } from './typescript.ts'
import { searchA_2dMatrix as searchA_2dMatrixJs } from './javascript.js'

test(`searchA_2dMatrix`, () => {
  expect(searchA_2dMatrix([[1,3,5,7],[10,11,16,20],[23,30,34,60]], 3)).toBe(true)
  expect(searchA_2dMatrix([[1,3,5,7],[10,11,16,20],[23,30,34,60]], 13)).toBe(false)
})

test(`searchA_2dMatrixJs`, () => {
  expect(searchA_2dMatrixJs([[1,3,5,7],[10,11,16,20],[23,30,34,60]], 3)).toBe(true)
  expect(searchA_2dMatrixJs([[1,3,5,7],[10,11,16,20],[23,30,34,60]], 13)).toBe(false)
})