首页 > 其他分享 >[Typescript] 126. Hard - Two Sum

[Typescript] 126. Hard - Two Sum

时间:2022-12-04 22:45:10浏览次数:64  
标签:Typescript false _____________ type Sum Two extends Expect true

Given an array of integers nums and an integer target, return true if two numbers such that they add up to target.

/* _____________ Your Code Here _____________ */
type NumberToArray<N, ACC extends any[] = []> = ACC['length'] extends N ? ACC: NumberToArray<N, [...ACC, 1]>;

type RecursiveAdd<Current extends number, T extends number[], Target extends number> = T extends [infer F, ...infer RT extends number[]]
  ? [...NumberToArray<F>, ...NumberToArray<Current>]['length'] extends Target
    ? true
    : RecursiveAdd<Current, RT, Target>
  : false;

type TwoSum<T extends number[], U extends number> = T extends [infer F extends number, ...infer RT extends number[]]
  ? RecursiveAdd<F, RT, U> extends false
    ? TwoSum<RT, U>
    : true
  : false;

/* _____________ Test Cases _____________ */
import type { Equal, Expect } from '@type-challenges/utils'

type cases = [
  Expect<Equal<TwoSum<[3, 3], 6>, true>>,
  Expect<Equal<TwoSum<[3, 2, 4], 6>, true>>,
  Expect<Equal<TwoSum<[2, 7, 11, 15], 15>, false>>,
  Expect<Equal<TwoSum<[2, 7, 11, 15], 9>, true>>,
  Expect<Equal<TwoSum<[1, 2, 3], 0>, false>>,
  Expect<Equal<TwoSum<[1, 2, 3], 1>, false>>,
  Expect<Equal<TwoSum<[1, 2, 3], 2>, false>>,
  Expect<Equal<TwoSum<[1, 2, 3], 3>, true>>,
  Expect<Equal<TwoSum<[1, 2, 3], 4>, true>>,
  Expect<Equal<TwoSum<[1, 2, 3], 5>, true>>,
  Expect<Equal<TwoSum<[1, 2, 3], 6>, false>>,
]

 

标签:Typescript,false,_____________,type,Sum,Two,extends,Expect,true
From: https://www.cnblogs.com/Answer1215/p/16951038.html

相关文章