TypeScript

博客分类: 江河计划

TypeScript

算法

爬楼问题

假设你正在爬楼梯。需要 n 阶你才能到达楼顶。

每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶呢?

注意:给定 n 是一个正整数。

示例 1:

输入: 2
输出: 2
解释: 有两种方法可以爬到楼顶。
1.  1 阶 + 1 阶
2.  2 阶

解法和费布那切的解法类似。

var climbStairs = function(n) {
    let arr = new Array(n)
    for(let i = 1; i <= n; i++) {
        if(i < 3) {
            arr[i - 1] = i
        } else {
            arr[i - 1] = arr[i - 2] + arr[i - 3]
        }
    }
    return n <= 0 ? 0 : arr[n - 1]
}

买卖股票的最佳时机

给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。

如果你最多只允许完成一笔交易(即买入和卖出一支股票),设计一个算法来计算你所能获取的最大利润。

注意你不能在买入股票前卖出股票。

示例 1:

输入: [7,1,5,3,6,4]
输出: 5
解释: 在第 2 天(股票价格 = 1)的时候买入,在第 5 天(股票价格 = 6)的时候卖出,最大利润 = 6-1 = 5 。
     注意利润不能是 7-1 = 6, 因为卖出价格需要大于买入价格。
var maxProfit = function(prices) {
    var total = 0;
    var min = prices[0];
    for(let i=1; i<prices.length; i++){
        total = Math.max(total, prices[i] - min);
        min = Math.min(min, prices[i]);
    }
    return total
};

typescript

基本类型

接口

interface LabelledValue {
  label: string;
  // 可选
  color?: string;
  // 只读
  readonly x: number;
}

函数接口

interface SearchFunc {
  (source: string, subString: string): boolean;
}

接口实现

interface ClockInterface {
    currentTime: Date;
    setTime(d: Date);
}

class Clock implements ClockInterface {
    currentTime: Date;
    setTime(d: Date) {
        this.currentTime = d;
    }
    constructor(h: number, m: number) { }
}

接口继承

interface Shape {
    color: string;
}

interface Square extends Shape {
    sideLength: number;
}

let square = <Square>{};
square.color = "blue";
square.sideLength = 10;

class Person {
    protected name: string;
    protected constructor(theName: string) { this.name = theName; }
}

// Employee 能够继承 Person
class Employee extends Person {
    private department: string;

    constructor(name: string, department: string) {
        super(name);
        this.department = department;
    }

    public getElevatorPitch() {
        return `Hello, my name is ${this.name} and I work in ${this.department}.`;
    }
}

let howard = new Employee("Howard", "Sales");

类的修饰符

函数类型

function add(x: number, y: number): number {
    return x + y;
}

declare

声明 ts 中的全局变量,比如在 window,不然使用的时候会报错。

declare var foo: number;
declare function greet(greeting: string): void;

修饰符

功能强大,用于函数包装