算法-爱奇艺春招笔试题

爱奇艺笔试题

一共两题还是比较简单的

第一题

题目

有A,B,C三个数和如下两个操作:1.任意两个数+1,2.一个数+2,假设经过有限步操作一定能使得3个数相等,问最少的操作次数

思路

排序后较小的两个数转为最大的数其实不管用1还是2方法步数一样,比如3,3,5使用两次1还是使用2次2都是得到最终结果,所以只要以最小的次数将最小的数转换为中间大小的数(加2)最后加上最大数与它的差值即可,这里有个问题是如果最小的和中间的不是同奇偶的话,最小数只能先转为中间大小-1,然后最小和最大同时+1,这样最小与中间相等了

代码
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        while(in.hasNext()){
            int a = in.nextInt(), b = in.nextInt(), c = in.nextInt();
            System.out.println(solve(a, b, c));
        }
    }

    private static int solve(int a, int b, int c) {
        int []arr = new int[]{a,b,c};
        Arrays.sort(arr);
        int ans = 0;
        int pre = arr[1] - arr[0];
        ans += (pre >> 1);//最小转换为中间需要几步
        arr[0] += 2 * ans;
        if(arr[0] != arr[1]){//不是同奇偶
            arr[0]++;
            arr[2]++;
            ans++;
        }
        ans += (arr[2] - arr[1]);
        return ans;
    }
}

第二题

题目

给定一个字符串,可以删除其中一部分字符获得他的子字符串,求字典顺序最大的子字符串

思路

首先两个字符串(s1,s2)字典顺序大小指的是从第一个字符开始比较如果s1[0] > s1[1],则是大,相等则向后比较例如”ac” > “ab”(因为’a’==’a’,’c’ > ‘b’)。在这一点基础上很容易得到思路,从后往前找如果当前字符大于当前子字符串第一个字符则加入,这样所得子字符串第一个字符一定是原字符串最大字符,第二个为次大,依次类推(最后一个肯定加入)

代码
public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        while(in.hasNext()){
            String str = in.nextLine();
            System.out.println(solve(str));
        }
        in.close();
    }

    private static String solve(String str) {
        final int len = str.length();
        if(len <= 1)
            return str;
        char max = str.charAt(len - 1);
        StringBuilder sb = new StringBuilder();
        sb.append(str.charAt(len - 1));
        for(int i = len - 2;i >=0;i--){
            final char c = str.charAt(i);
            if(c >= max){
                sb.insert(0, c);
                max = c;
            }
        }
        return sb.toString();
    }
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值