最小的K个数&&连续子数组的最大和

最小的K个数

输入n个整数,找出其中最小的K个数。例如输入4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1,2,3,4,。

解题思路

遍历数组,每次找到最小的取出来,完成k次遍历,找出最小的k个数

代码

import java.util.ArrayList;

public class jzo29 {
    public ArrayList<Integer> GetLeastNumbers_Solution(int [] input, int k) {
        ArrayList<Integer> result=new ArrayList<>();
        if(k>input.length){
            return result;
        }
        for (int i=0;i<k;i++){
            for (int j=0;j<input.length-i-1;j++)
                if (input[j] < input[j + 1]) {
                    int tmp = input[j];
                    input[j] = input[j + 1];
                    input[j + 1] = tmp;
                }
            result.add(input[input.length-i-1]);
        }
        return result;
    }
    public static void main(String[] args){
        int[] tmp={4,5,1,6,2,7,3,8};
        int k=4;
        jzo29 so=new jzo29();
        System.out.println(so.GetLeastNumbers_Solution(tmp,k));
    }
}

连续子数组的最大和

HZ偶尔会拿些专业问题来忽悠那些非计算机专业的同学。今天测试组开完会后,他又发话了:在古老的一维模式识别中,常常需要计算连续子向量的最大和,当向量全为正数的时候,问题很好解决。但是,如果向量中包含负数,是否应该包含某个负数,并期望旁边的正数会弥补它呢?例如:{6,-3,-2,7,-15,1,2,2},连续子向量的最大和为8(从第0个开始,到第3个为止)。给一个数组,返回它的最大连续子序列的和,你会不会被他忽悠住?(子向量的长度至少是1)

解题思路

  1. 如果array中全是负数,最大累计和就是数组中的最大值
  2. 如果array全是正数,最大累计和就是所有元素相加
  3. array中有正数有负数,从左到右遍历array,用变量current记录每一步的累加和,遍历到正数,current增加,遍历到负数current减少。当current<0,累加当前数出现了小于0,所以累加到这一部分不能作为最大累加和的子数组的左边部分。。令current=0,表示从下一个数开始累计。当current>=0,每一次累加都可能是最大的累加和,用max记录current出现的最大值。

代码

public class jzo30 {
    public int FindGreatestSumOfSubArray(int[] array) {
        if (array==null||array.length==0){
            return 0;
        }
        int max=Integer.MIN_VALUE;
        int current=0;
        for (int i=0;i!=array.length;i++){
            current+=array[i];
            max=Math.max(max,current);
            current=current<0?0:current;
        }
        return max;
    }
    public static void main(String[] args){
        int[] arr={1,-2,3,5,-2,6,-1};
        jzo30 so=new jzo30();
        System.out.println(so.FindGreatestSumOfSubArray(arr));
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值