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

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

  • 8
    点赞
  • 56
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 12
    评论
LeetCode和牛客网都是在线编程练习平台,供程序员进行算法和编程题目的练习。两个平台有一些区别。 LeetCode是一个以算法为主的平台,题目描述简练,直奔主题,通常使用英文进行描述。LeetCode注重算法思维和解题能力的锻炼,题目更偏向于算法数据结构的应用。许多人在LeetCode上进行练习,习惯了它的题目风格和解题模式。 而牛客网是一个综合性的在线编程平台,除了算法题,还包括面试题、笔试题、实习生项目等。牛客网的题目描述相对LeetCode来说更加贴近实际场景,有更多的描述和背景信息。这也可能导致牛客网的题目相对较长,需要花费一些时间来阅读和理解。 不同的人对于这两个平台的喜好和适应程度各有差异。有的人可能习惯于LeetCode的简练风格,而对牛客网的题目描述感到吃力;有的人则喜欢牛客网提供的更多背景和场景信息。 总的来说,LeetCode和牛客网都是很好的编程练习平台,可以根据个人的需要和喜好进行选择和使用。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [LeetCode和牛客网的对比](https://blog.csdn.net/zr1076311296/article/details/51606300)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]
评论 12
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

code tea

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值