牛客网笔试输入的问题(Java)

今天在做滴滴出行内推笔试的编程题碰到了这个问题耽误了很长时间,然而网上也没有答案,因此记录下来,方便自己查阅复习,也方便需要的小伙伴!

代码如下-----滴滴2018内推的编程题:

package 内推笔试;

import java.util.Arrays;
import java.util.Scanner;

/**
 * Created by liuming on 2017/8/26.
 */
public class 滴滴 {

    /**
     * 给定整数序列求最大连续字串和
     * <p>
     * 问题描述:
     * 给定无序正数序列,求连续字串最大和,例如:{-23,17,-7,11,-2,1,34},字串为{17,-7,11,},最大和为21
     */
    public static int getTargetMax(int[] arr) {
        int max = arr[0];
        int tmpMax = arr[0];
        for (int i = 1; i < arr.length; i++) {
            if (tmpMax <= 0)
                tmpMax = arr[i];
            else
                tmpMax += arr[i];
            if (tmpMax > max) {
                max = tmpMax;
            }
        }
        return max;
    }

    public static void main1(String[] args) {
        Scanner sc = new Scanner(System.in);
        //获取输入的整数序列
        String str = sc.nextLine();
        String[] strings = str.split(" ");
        //转为整数数组
        int[] ints = new int[strings.length];
        for (int i = 0; i < strings.length; i++) {
            ints[i] = Integer.parseInt(strings[i]);
        }
        System.out.println(getTargetMax(ints));
    }

    /**
     * 整数无序数组求第K大数
     * <p>
     * 问题描述:
     * 给定无序整数序列,求其中第K大的数,例如{45,67,33,21},第2大的数为45
     */
    public static int getTopK(int[] arr, int k) {
        Arrays.sort(arr);
        return arr[arr.length - k];
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        //获取输入的整数序列
        String str = sc.nextLine();
        String[] strings = str.split(" ");
        //转为整数数组
        int[] ints = new int[strings.length];
        for (int i = 0; i < strings.length; i++) {
            ints[i] = Integer.parseInt(strings[i]);
        }
        int k = sc.nextInt();
        System.out.println(getTopK(ints, k));
    }

}


Reference:http://blog.csdn.net/sinat_22840937/article/details/77603602

  • 3
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值