笔试狂刷--Day5(最小公倍数+最优路径)

大家好,我是LvZi,今天带来笔试狂刷--Day5
在这里插入图片描述

一.求最小公倍数

链接:求最小公倍数
在这里插入图片描述

分析:

数学知识–辗转相除法(迭代/递归)

代码:

import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int a = in.nextInt(), b = in.nextInt();
        System.out.println((a * b) / gcd(a,b));
    }

    private static int gcd(int a, int b) {
        if(b == 0) return a;
        return gcd(b, a % b);
    }
}

二.数组中最长连续子序列

链接:数组中最长连续子序列
分析:

排序 + 双指针

代码:

import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * max increasing subsequence
     * @param arr int整型一维数组 the array
     * @return int整型
     */
    public int MLS (int[] arr) {
        // write code here
        Arrays.sort(arr);// 先排序

        int ret = 0;
        for(int i = 0; i < arr.length;) {
            int j = i + 1, cnt = 1;
            while(j < arr.length) {
                if(arr[j] - arr[j - 1] == 1) {
                    cnt++; j++;// 连续  ++
                }else if(arr[j] == arr[j - 1]) {
                    j++;// 相等的数字应该只记录一次
                }else {
                    break;
                }
            }

            ret = Math.max(ret, cnt);
            i = j;// 更新下标
        }

        return ret;
    }
}

总结:

  • 注意前后两个数字相等的情况,此时应该只记录一次
  • j的作用是作为一个指针遍历数组中的每一个元素,由于存在相同数字的情况,不能仅仅根据j - i + 1来更新结果,所以额外开辟一个变量cnt来记录连续数字的个数

三.字母收集

链接:字母收集

在这里插入图片描述

分析:

dp经典路径问题

代码:

import java.util.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        // 处理输入
        Scanner in = new Scanner(System.in);
        int m = in.nextInt(), n = in.nextInt();
        char[][] arr  = new char[m][n];
        for(int i = 0; i < m; i++) {
            String tmp = in.next();
            for(int j = 0; j < n; j++) {
                arr[i][j] = tmp.charAt(j);
            }
        }

        Map<Character,Integer> hash = new HashMap<>();// 建立映射关系
        hash.put('l',4); hash.put('o',3);
        hash.put('v',2); hash.put('e',1);

        int[][] dp = new int[m + 1][n + 1];
        for(int j = 2; j <= n; j++) dp[0][j] = -0x3f3f3f3f;// 初始化
        for(int i = 2; i <= m; i++) dp[i][0] = -0x3f3f3f3f;// 初始化

        // 填表
        for(int i = 1; i <= m; i++) {
            for(int j = 1; j <= n; j++) {
                int core = hash.getOrDefault(arr[i - 1][j - 1],0);// 计算当前位置的值
                dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]) + core;
            }
        }

        System.out.println(dp[m][n]);
    }
}
  • 10
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值