牛客网 - 华为OD算法机试(可内推)

2023-11-06

1.前言

这几天在闭关修炼数据结构和算法, 也好几天没有更新博客了。
其实我也没学多久的算法, 满打满算牛客和leecode也就刷了四十来道题。
其实算法也没有我们一开始想象的那么难, 至少面试考的算法都还比较基础。
今天参加了华为OD的机试, 没有想象中的那么难, 但是还是熟练度的问题, 加上第一次考试有点紧张。前两题过了100%的用例, 用时一小时, 后面一个半小时都在刚第三题, 结果自己对递归的返回值处理不到位, 相当于没过吧, 晚上抽时间把代码调整了下, 应该是能正常跑过了。
现在把我经历的三道题分享出来, 有兴趣或者有建议的大佬的可以在我的博客留言。

建议看完题意后先自己思考怎么实现
本文题解只能实现功能, 并不是最优算法

ps: 一面 / 二面 也结束了, 我做了一些总结, 有兴趣可以看我这篇博客
华为od一面 / 二面复盘

第一题: 求剩余扑克牌最大顺子问题 100分

题意

扑克牌为 345678910JQKA 每种牌4张
输入是你现在的手牌, 还有已经打出去的牌

求剩下的牌中能凑出来的最大的顺子是多少
这里顺子的大小优先比较长度, 相同长度的顺子则比较牌面大小
比如:
你的手牌 3-3-3-8-8-8-8
已经打出的牌 4-4-5-5-6-6
最大的顺子是 9-10-J-Q-K-A

题解

import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        //手牌
        String s1 = sc.nextLine();
        //出过的牌
        String s2 = sc.nextLine();

        //初始化
        HashMap<String, Integer> count = new HashMap<>(16);
        for (int i = 3; i <= 10; i++) {
            count.put(String.valueOf(i), 4);
        }
        count.put("J", 4);
        count.put("Q", 4);
        count.put("K", 4);
        count.put("A", 4);

        String[] ss1 = s1.split("-");
        for (int i = 0; i < ss1.length; i++) {
            count.put(ss1[i], count.get(ss1[i]) - 1);
        }
        String[] ss2 = s2.split("-");
        for (int i = 0; i < ss2.length; i++) {
            count.put(ss2[i], count.get(ss2[i]) - 1);
        }


        //最大长度,队列, 读到0就输出前面的串
        String[] sa = new String[]{"3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A"};
        Deque<String> list = new LinkedList<>();
        //从大的开始
        String result = null;
        int max = 0;
        for (int i = sa.length - 1; i >= 0; i--) {
            if (count.get(sa[i]) > 0) {
                list.offerFirst(sa[i]);
            } else {
                //读到0了, 看能不能组成顺子
                if (list.size() < 5) {
                    list.clear();
                } else {
                    if (list.size() > max) {
                        max = list.size();
                        String tem = "";
                        while (list.size() > 0) {
                            tem += list.pollFirst() + "-";
                        }
                        result = tem.substring(0, tem.length() - 1);
                    }else{
                        list.clear();
                    }
                }
            }
        }

        //读到头 处理剩余数据
        if (list.size() >= 5 && list.size() > max) {
            max = list.size();
            String tem = "";
            while (list.size() > 0) {
                tem += list.pollFirst() + "-";
            }
            result = tem.substring(0, tem.length() - 1);
        }

        if (max == 0) {
            System.out.println("NO-CHAIN");
        } else {
            System.out.println(result);
        }
    }
}

第二题: 一系列正整数, 从中取三个数拼接后的最小数字 100分

题意

给你一系列数字, 从中取出三个数字, 如果给的数字不到三个有几个取几个
求这几个数字拼接后的最小数字是多少。

比如:
给定 18,123,22,5,12,34,23,43,344,21
拼接后的最小数字是 12,18,5的拼接, 12185

这道题比较简单, 注意边界条件的处理, 而且数字可能超长

题解

import java.math.BigDecimal;
import java.util.*;

public class Main2 {

    static BigDecimal min;

    static String[] choice = new String[3];

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
        String s = sc.nextLine();
        String[] ss = s.split(",");

        if (ss.length == 0) {
            System.out.println(0);
            return;
        } else if (ss.length == 1) {
            System.out.println(ss[0]);
            return;
        } else if (ss.length == 2) {
            System.out.println(Math.min(Integer.parseInt(ss[0] + ss[1]),
                    Integer.parseInt(ss[1] + ss[0])));
            return;
        }


        //数组长度为3及以上,取三个长度最短的, 相等的都取出来
        //截取0后长度最短的
        PriorityQueue<String> queue = new PriorityQueue<>(new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                return new BigDecimal(o1).compareTo(new BigDecimal(o2));
            }
        });

        for (int i = 0; i < ss.length; i++) {
            queue.offer(ss[i]);
        }

        choice[0] = queue.poll();
        choice[1] = queue.poll();
        choice[2] = queue.poll();

        //最小数字
        min = new BigDecimal(choice[0] + choice[1] + choice[2]);

        int[] ids = new int[3];
        for (int i = 0; i < 3; i++) {
            int[] idsCopy = Arrays.copyOf(ids, ids.length);
            idsCopy[i] = 1;
            build(idsCopy, 0, i, "");
        }
        System.out.println(min);
    }


    public static void build(int[] ids, int count, int index, String s) {
        s += choice[index];
        if (count == 2) {
            BigDecimal bigDecimal = new BigDecimal(s);
            if (bigDecimal.compareTo(min) < 0) {
                min = bigDecimal;
            }
            return;
        }

        for (int i = 0; i < 3; i++) {
            int[] idsCopy = Arrays.copyOf(ids, ids.length);
            if (idsCopy[i] != 1) {
                idsCopy[i] = 1;
                build(idsCopy, count + 1, i, s);
            }
        }
    }
}

第三题: 两人野营, 求两人能共同到达的聚餐点数量

题意

给定一个m*n的矩阵, 矩阵中数字 0 代表空地, 可通过, 1 代表障碍, 不可通过, 数字 2 代表两个人所在的位置, 3代表聚餐点所在的位置。
求两个人同时能够到达的聚餐点有多少个?

比如:
给定, 第一行的两个数字分别是m, n
4 4
2 1 0 3
0 1 2 1
0 3 0 0
0 0 0 0
求得 2

题解

public class Main3 {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String s = sc.nextLine();
        String[] ss = s.split(" ");
        //长
        m = Integer.parseInt(ss[0]);
        //宽
        n = Integer.parseInt(ss[1]);

        List<Pos> eatPos = new ArrayList<>();
        int[][] serched = new int[m][n];

        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                int point = sc.nextInt();
                if (point == 3) {
                    eatPos.add(new Pos(i, j));
                }
                if (point == 1) {
                    serched[i][j] = 1;
                }
                arr[i][j] = point;
            }
        }

        if (eatPos.size() == 0) {
            System.out.println(0);
            return;
        }


        for (Pos eat : eatPos) {
            //从聚餐点可以到达几个人, 如果能到达两个人, 则可达聚餐点+1
            int personFlag = 0;

            Pos left = eat.left();
            Pos right = eat.right();
            Pos up = eat.up();
            Pos down = eat.down();
            serched[eat.x][eat.y] = 1;
            //上下左右
            personFlag = search(left.x, left.y, personFlag, serched);
            if (personFlag == 2) {
                result++;
                continue;
            }
            personFlag = search(right.x, right.y, personFlag, serched);
            if (personFlag == 2) {
                result++;
                continue;
            }
            personFlag = search(up.x, up.y, personFlag, serched);
            if (personFlag == 2) {
                result++;
                continue;
            }
            personFlag = search(down.x, down.y, personFlag, serched);
            if (personFlag == 2) {
                result++;
            }
        }

        System.out.println(result);
    }

    static int m;
    static int n;

    static int result = 0;
    static int[][] arr = new int[99][99];

    /**
     * @param x          找的下一个点
     * @param y          找的下一个点
     * @param personFlag 记录已经找到的人数, 找到2个人就成功, 给答案+1
     * @param searched   记录已经找过的点
     */
    public static int search(int x, int y, int personFlag, int[][] searched) {
        if (!isValid(x, y, searched)) {
            return personFlag;
        }
        if (arr[x][y] == 2) {
            personFlag++;
        }
        if (personFlag == 2) {
            return personFlag;
        }

        int[][] serchedCopy = new int[m][n];
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                serchedCopy[i][j] = searched[i][j];
            }
        }
        serchedCopy[x][y] = 1;

        Pos current = new Pos(x, y);
        Pos left = current.left();
        Pos right = current.right();
        Pos up = current.up();
        Pos down = current.down();
        //上下左右
        personFlag = search(left.x, left.y, personFlag, serchedCopy);
        if (personFlag == 2) {
            return personFlag;
        }
        personFlag = search(right.x, right.y, personFlag, serchedCopy);
        if (personFlag == 2) {
            return personFlag;
        }
        personFlag = search(up.x, up.y, personFlag, serchedCopy);
        if (personFlag == 2) {
            return personFlag;
        }
        personFlag = search(down.x, down.y, personFlag, serchedCopy);
        return personFlag;
    }

    /**
     * 是否在边界内而且没找过
     */
    public static boolean isValid(int x, int y, int[][] searched) {
        if (x >= m || x < 0 || y >= n || y < 0) {
            return false;
        }
        if (searched[x][y] == 1) {
            return false;
        }
        return true;
    }


    static class Pos {
        int x;
        int y;

        public Pos(int x, int y) {
            this.x = x;
            this.y = y;
        }

        public Pos left() {
            return new Pos(x, y - 1);
        }

        public Pos right() {
            return new Pos(x, y + 1);
        }

        public Pos up() {
            return new Pos(x - 1, y);
        }

        public Pos down() {
            return new Pos(x + 1, y);
        }

    }


    public static void print(int[][] arr) {
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                System.out.print(arr[i][j] + " ");
            }
            System.out.println();
        }
    }
}

优化-动态规划

上面的解法非常的粗糙, 优点在于方便理解回溯的思想
实际上基于动态规划我们可以做一些优化,

一个是探索过的路径我们不需要重复探索, 因为我们都是从上下左右四个方向探索的, 所以我引入了searched数组, 用来记录已经探索过的坐标

第二个是剪枝操作, 只要在探索的过程中, 从一个聚餐点(数字3)出发已经能到达两个人(数字2), 那么我们就不需要继续探索, 直接return
我把return统一放到回溯方法的前面, 代码上要简洁一些

还有一个就是备忘录, 比如我们从一个聚餐点出发, 探索完这个聚餐点的可达路径后, 如果我们能够同时到达两个人, 那么很明显, 所有我们探索过程中探索过的坐标都能到达两个人(这体现了动态规划重复子问题的特点)
那么我们可以把searched数组缓存起来, 探索其他聚餐点的时候先从缓存获取即可。如果最终只能到达1个人, 或者0个人, 同样的, 我们也是缓存起来就行, 因为结果是一样的。

这样, 最终我们所有的点只需要探索一遍, 也就是时间复杂度O(mn), 空间复杂度我们对每个3节点引入了searched数组记录探过的路径, 引入一个cache数组来缓存子问题结果, 空间复杂度是O(mn)

public class Main {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String s = sc.nextLine();
        String[] ss = s.split(" ");
        //长
        m = Integer.parseInt(ss[0]);
        //宽
        n = Integer.parseInt(ss[1]);

        List<Pos> eatPos = new ArrayList<>();

        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                int point = sc.nextInt();
                if (point == 3) {
                    eatPos.add(new Pos(i, j));
                }
                arr[i][j] = point;
            }
        }

        if (eatPos.size() == 0) {
            System.out.println(0);
            return;
        }


        for (Pos eat : eatPos) {
            //从聚餐点可以到达几个人, 如果能到达两个人, 则可达聚餐点+1

            //初始化
            int personFlag = 0;
            int[][] searched = new int[m][n];

            //上下左右
            personFlag = search(eat.x, eat.y, personFlag, searched);
            if (personFlag == 2) {
                result++;
            }

            //缓存起来
            for (int i = 0; i < m; i++) {
                for (int j = 0; j < n; j++) {
                    cache[i][j] = searched[i][j];
                }
            }
        }

        System.out.println(result);
    }

    static int m;
    static int n;

    static int result = 0;
    static int[][] arr = new int[99][99];

    //缓存, 只要最后能到达2个人, 那么所有搜索走过的路径都能到达2个人
    static int[][] cache = new int[99][99];

    /**
     * @param x          找的下一个点
     * @param y          找的下一个点
     * @param personFlag 记录已经找到的人数, 找到2个人就成功, 给答案+1
     * @param searched   记录已经找过的点
     */
    public static int search(int x, int y, int personFlag, int[][] searched) {
        //不合法/找过的路不走
        if (!isValid(x, y, searched)) {
            return personFlag;
        }
        if (cache[x][y] == 2) {
            return cache[x][y];
        }
        searched[x][y] = 1;
        //找到人, 人数+1
        if (arr[x][y] == 2) {
            personFlag++;
        }
        //人数=2, 结束
        if (personFlag == 2) {
            return personFlag;
        }

        Pos current = new Pos(x, y);
        Pos left = current.left();
        Pos right = current.right();
        Pos up = current.up();
        Pos down = current.down();
        //上下左右
        personFlag = search(left.x, left.y, personFlag, searched);
        personFlag = search(right.x, right.y, personFlag, searched);
        personFlag = search(up.x, up.y, personFlag, searched);
        personFlag = search(down.x, down.y, personFlag, searched);
        return personFlag;
    }

    /**
     * 是否在边界内而且没找过
     */
    public static boolean isValid(int x, int y, int[][] searched) {
        if (x >= m || x < 0 || y >= n || y < 0) {
            return false;
        }
        return arr[x][y] != 1 && searched[x][y] != 1;
    }


    static class Pos {
        int x;
        int y;

        public Pos(int x, int y) {
            this.x = x;
            this.y = y;
        }

        public Pos left() {
            return new Pos(x, y - 1);
        }

        public Pos right() {
            return new Pos(x, y + 1);
        }

        public Pos up() {
            return new Pos(x - 1, y);
        }

        public Pos down() {
            return new Pos(x + 1, y);
        }

    }
}

ps:看到这里,我们部门最近还有人力需求。部门业务是华为云计算,位置在杭州研究所,有意向的可以私聊。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

牛客网 - 华为OD算法机试(可内推) 的相关文章

随机推荐

  • oracle时间获取记录

    select trunc sysdate from dual 2017 9 11 select trunc sysdate 1 from dual 2017 9 12 select sysdate from dual 从系统获取时间2017
  • VsCode怎么打开settings.json文件?

    Mac command shift p 输入setting json 选择 首选项 打开设置 json 即可
  • 使用Git进行版本控制,并将代码托管到GitHub的完整流程

    Git是一个分布式版本控制系统 它可以记录文件的修改历史 并且可以管理多人协作开发的项目 Git的基本工作流程如下 在开发者的本地电脑上安装Git 并克隆一个GitHub上已存在的项目到本地 在本地进行代码的修改和提交 这些修改都会被存储在
  • Android studio编译中Connect to maven.google.com:443[xxx] failed: connect timed out的解决方法

    前言 最近徒弟分到了一个rn的模块开发工作 但rn 大家懂的 Android studio有时需要科学上网下载必要的rn库 又是一个徒弟哀嚎的日子 问题 连接maven google com超时 具体编译报错如下 gt Could not
  • R语言-- R语言数据类型(3)

    列表 创建 1 1 创建一个列表L1 记录三位同学的姓名 A B C 编号 1 2 3 数学成绩 80 90 95 语文成绩 75 95 80 L1 lt list 姓名 c A B C 编号 c 1 2 3 数学 c 80 90 95 语
  • VPP代码阅读中文注解---dlmalloc.h

    Quickstart This library is all in one file to simplify the most common usage ftp it compile it O3 and link it into anoth
  • 大数据课程L3——网站流量项目的系统搭建

    文章作者邮箱 yugongshiye sina cn 地址 广东惠州 本章节目的 了解网站流量项目的运行环境 了解网站流量项目的日志采集系统搭建 了解网站流量项目的离线业务系统搭建 了解网站流量项目的Hive做离线数据处理 了解网站流量项目
  • js解leetcode(44)-简单

    1 有多少小于当前数字的数字 题目 给你一个数组 nums 对于其中每个元素 nums i 请你统计数组中比它小的所有数字的数目 换而言之 对于每个 nums i 你必须计算出有效的 j 的数量 其中 j 满足 j i 且 nums j l
  • Linux 下bsub命令

    一 bsub bsub 提交给lsf作业的命令 命令格式 bsub options command argument bsub pack job submission file q 选择队列 i 指定输入文件 I 交互模式 此时终端不能输入
  • RabbitMQ和Kafka的区别

    RabbitMQ 和 Apache Kafka 是两种流行的消息传递系统 它们具有不同的设计目标和适用场景 以下是它们的主要区别 消息传递模型 RabbitMQ RabbitMQ 是一个传统的消息队列系统 采用了基于消息队列的发布 订阅模型
  • 关于压缩感知的基本原理

    转自https blog csdn net wanz2 article details 52770095 该博客中作者介绍了传统的压缩和压缩感知 并且介绍了匹配追踪算法OMP的基本原理 让我看明白点了OMP算法 但是有一个疑问 如果不知道信
  • Unity下载大文件断点续传

    最近要使用安卓更新下载apk更新功能 由于安卓机运行内存有限 下载大文件就得采用实时下载写入 实时释放内存的方法 考虑到网络环境不稳定时下载被迫中断的情况 重新从头下载会导致不必要的资源浪费 断点续传也很有必要 UnityWebReques
  • 计算机网络第七版--概述知识点总结

    计算机网络第七版 谢希仁 第一章 概述 1 1 计算机网络在信息时代的应用 21世纪的一些重要的特征就是数字化 网络化和信息化 它是一个以网络为核心的信息时代 互联网具有两个重要的特点 连通性 交换各种信息 和共享 资源共享 1 2 互联网
  • Java核心——集合(一)接口

    集合框架围绕一组标准接口而设计 我们可以直接使用这些接口的标准实现 例如 LinkedList HashSet TreeSet等 除此之外还可以通过这些接口实现自己的集合 集合框架是一个用来代表和操纵集合的统一架构 所有的集合框架都包含如下
  • Visual Studio 2019中创建的C++项目无法使用万能头<bits/stdc++.h>解决方案

    Visual Studio 2019创建C 项目无法使用万能头
  • 很有意思的一个自定义CGI,用BAT文件做的。大家发挥想象,自己发挥哈~

    httpd conf ScriptAlias bat d test AddType application x httpd bat bat Action application x httpd bat bat aaa bat aaa bat
  • 【C++笔记】C++11常用特性的使用经验总结

    转载 https www cnblogs com feng sc p 5710724 html title12
  • php getmimetype,wordpress关于日志的常用函数get_post_mime_type()

    说明 按ID编号检索附件的mime类型 该函数可用于任何文章类型 但更适用于附件类型 用法 参数 ID 整数 可选 文章ID 默认值 返回的值 布尔型 字符 返回mime类型 出错时则返回False 示例 mime type get pos
  • DirectShow--用GraphEdit辅助调试

    前面的话 GraphEdit 微软的SDK里面有个DirectShow的辅助工具GraphEdit 这里的文字简单介绍如何将应用程序生成的GraphBuilder插入到GraphEdit中直观的显示 可能一开始我们对这种应用有点儿不理解 既
  • 牛客网 - 华为OD算法机试(可内推)

    1 前言 这几天在闭关修炼数据结构和算法 也好几天没有更新博客了 其实我也没学多久的算法 满打满算牛客和leecode也就刷了四十来道题 其实算法也没有我们一开始想象的那么难 至少面试考的算法都还比较基础 今天参加了华为OD的机试 没有想象