TypeScript 及算法准备

avatar
作者
猴君
阅读量:0
TypeScript 基础
  1. 类型注解:为变量、函数参数和返回值指定类型。

    typescript复制代码let count: number = 10;  function greet(name: string): string {   return `Hello, ${name}!`; }
  2. 接口和类型别名:定义对象结构和复杂类型。

    typescript复制代码interface User {   id: number;   name: string; }  type ID = number | string;
  3. 泛型:创建可重用的组件。

    typescript复制代码function identity<T>(arg: T): T {   return arg; }  let output = identity<string>("Hello");
  4. 类和接口:面向对象编程。

    typescript复制代码class Animal {   name: string;   constructor(name: string) {       this.name = name;   }   move(distance: number = 0) {       console.log(`${this.name} moved ${distance}m.`);   } }  interface Flying {   fly(distance: number): void; }  class Bird extends Animal implements Flying {   fly(distance: number) {       console.log(`${this.name} flew ${distance}m.`);   } }

算法准备:数组扁平化

数组扁平化是指将多维数组转换为一维数组。以下是几种实现方式:

  1. 使用递归

    typescript复制代码function flattenArray(arr: any[]): any[] {   let result: any[] = [];   for (let item of arr) {       if (Array.isArray(item)) {           result = result.concat(flattenArray(item));       } else {           result.push(item);       }   }   return result; }  console.log(flattenArray([1, [2, [3, 4]], 5])); // [1, 2, 3, 4, 5]
  2. 使用reduce和递归

    typescript复制代码function flattenArray(arr: any[]): any[] {   return arr.reduce((acc, val) => Array.isArray(val) ? acc.concat(flattenArray(val)) : acc.concat(val), []); }  console.log(flattenArray([1, [2, [3, 4]], 5])); // [1, 2, 3, 4, 5]
  3. 使用栈

    typescript复制代码function flattenArray(arr: any[]): any[] {   const stack = [...arr];   const result: any[] = [];   while (stack.length) {       const next = stack.pop();       if (Array.isArray(next)) {           stack.push(...next);       } else {           result.push(next);       }   }   return result.reverse(); }  console.log(flattenArray([1, [2, [3, 4]], 5])); // [1, 2, 3, 4, 5]

算法题:两个有序数组合并成一个有序数组

合并两个有序数组并保持有序,可以使用双指针法。

typescript复制代码function mergeSortedArrays(arr1: number[], arr2: number[]): number[] {   let i = 0, j = 0;   const result: number[] = [];    while (i < arr1.length && j < arr2.length) {       if (arr1[i] < arr2[j]) {           result.push(arr1[i]);           i++;       } else {           result.push(arr2[j]);           j++;       }   }    // 处理剩余元素   while (i < arr1.length) {       result.push(arr1[i]);       i++;   }    while (j < arr2.length) {       result.push(arr2[j]);       j++;   }    return result; }  // 测试 const arr1 = [1, 3, 5, 7]; const arr2 = [2, 4, 6, 8]; console.log(mergeSortedArrays(arr1, arr2)); // [1, 2, 3, 4, 5, 6, 7, 8]

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!