zoukankan      html  css  js  c++  java
  • 算法(第4版)-1.1 练习(部分)

    1.1.3

    命令行的取参方法:

    1.StdIn.readInt():  java XX,运行,输入参数,以空格或换行隔开;

    2.Integer.parseInt(args[0]):  java XX 参数,以空格隔开,运行。

    1.1.6

    for (int i = 0; i <= 15; i++) {
        StdOut.println(f);
        f = f + g;
        g = f - g;
    }

    注意,当运行到g = f - g;这一行时,f已改变。

    1.1.8

    System.out.println('b' + 'c');

    答案:197

    “”表示String,‘’表示char。

    1.1.15

    // https://github.com/aistrate/AlgorithmsSedgewick
    public static int[] histogram(int[] a, int M)
    {
        int[] h = new int[M];
        int N = a.length;
        
        for (int i = 0; i < N; i++)
            if (a[i] < M)
                h[a[i]]++;
    
        return h;
    }

    理解题意,巧妙解决,不必写双重循环。

    1.1.19 *

    // https://github.com/aistrate/AlgorithmsSedgewick
    public static long Fib(int N)
    {
        long[] f = new long[N+1];
        return Fib(N, f);
    }
    
    public static long Fib(int N, long[] f)
    {
        if (f[N] == 0)
        {
            if (N == 1)
                f[N] = 1;
            else if (N > 1)
                f[N] = Fib(N-1, f) + Fib(N-2, f);
        }
        
        return f[N];
    }

    用数组保存已经计算过的值,更好地实现F(N)。

    实测证明,原方法几分钟才输出到40多,且后面越来越慢(根据题意1小时都不能全部输出),改进后的方法几乎是秒输出。性能差异巨大。

  • 相关阅读:
    【bzoj1191】 HNOI2006—超级英雄Hero
    【poj3020】 Antenna Placement
    【poj1274】 The Perfect Stall
    【poj2724】 Purifying Machine
    【poj2226】 Muddy Fields
    【codevs1257】 打砖块
    【poj2186】 Popular Cows
    【poj1236】 Network of Schools
    【poj1144】 Network
    【poj3177】 Redundant Paths
  • 原文地址:https://www.cnblogs.com/iguure/p/5965367.html
Copyright © 2011-2022 走看看