zoukankan      html  css  js  c++  java
  • 种花, 美团笔试题

    一、分治法

    时间复杂度:O(NlogN)

    通过70%样例,超时

    import java.util.*;
    public class Main {
        static int res = 0;
        static void solution(int[] a, int i, int j, int x) {
            if(i > j || i < 0 || i >= a.length || j < 0 || j >= a.length) return;
            int idx = i;
            for(int k = i+1; k <= j; k++) 
                if(a[k] < a[idx]) idx = k;
            res += (a[idx]-x);
            
            solution(a, i, idx-1, a[idx]);
            solution(a, idx+1, j, a[idx]);
        }
        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
            int n = sc.nextInt();
            int[] a = new int[n];
            for(int i=0; i < n; i++) {
                a[i] = sc.nextInt();
            }
            solution(a, 0, n-1, 0);
            System.out.println(res);
        }
    }
    

    二、贪心

    时间复杂度: O(N)

    import java.util.*;
    public class Main {
        static int res = 0;
        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
            int n = sc.nextInt();
            int[] a = new int[n];
            for(int i=0; i < n; i++) {
                a[i] = sc.nextInt();
            }
            int res = a[n-1];
            for(int i=1; i < n; i++) {
                if(a[i-1] > a[i])
                    res += a[i-1] - a[i];
            }
            System.out.println(res);
        }
    }
    

    三、动态规划

    时间复杂度:O(N)

    import java.util.*;
    public class Main {
        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
            int n = sc.nextInt();
            int[] a = new int[n];
            for(int i=0; i < n; i++) {
                a[i] = sc.nextInt();
            }
            int[] f = new int[n];
            f[0] = a[0];
            for(int i=1; i < n; i++) {
                if(a[i] > a[i-1])
                    f[i] = f[i-1] + a[i] - a[i-1];
                else
                    f[i] = f[i-1];
            }
            System.out.println(f[n-1]);
        }
    }
    /*
    f[i] 表示 完成前i个花园的种花计划最少要天数。
    a[i] <= a[i-1],  f[i] = f[i-1]
    否则, f[i] = f[i-1] + (a[i] - a[i-1])
    */
    
  • 相关阅读:
    C++多态性(静多态和动多态)
    根据二叉树的后序遍历以及中序遍历还原二叉树
    哈希表
    *********** 复习算法复杂度,基础 ************
    C++虚函数表解析
    为什么需要auto_ptr_ref
    python未修辞的计时器
    python删除一个非空文件夹竟然如此简单
    python模拟163登陆获取邮件列表
    wxpython制作eml文件阅读器
  • 原文地址:https://www.cnblogs.com/lixyuan/p/13185357.html
Copyright © 2011-2022 走看看