LintCode 最接近零的子数组和

本文介绍了一种寻找整数数组中最接近零和的子数组的方法,并提供了详细的算法实现。通过排序前缀和并比较相邻前缀和的差值,可以找到满足条件的子数组。

给定一个整数数组,找到一个和最接近于零的子数组。返回第一个和最右一个指数。你的代码应该返回满足要求的子数组的起始位置和结束位置

样例
给出[-3, 1, 1, -3, 5],返回[0, 2],[1, 3], [1, 1], [2, 2] 或者 [0, 4]。

任意子数组的和,可由两个前缀和相减得到。前缀和是指从数组第一个元素到数组中某个元素的子数组的和。题目要求子数组的和最接近零,那么就是要求两个前缀和之间的差最小。所以考虑把前缀和排序,然后依次比较相邻的两个前缀和(注意排序时要记录前缀和的下标(即原数组中哪个元素的前缀和))。

代码如下:

public class Solution {
    /*
     * @param nums: A list of integers
     * @return: A list of integers includes the index of the first number and the index of the last number
     */
    public int[] subarraySumClosest(int[] nums) {
        // write your code here
        Map<Integer,Integer> sum=new HashMap<Integer,Integer>();//用一个Map来存储<下标,前缀和>
        sum.put(0,nums[0]);
        for(int i=1;i<nums.length;i++){
            sum.put(i,sum.get(i-1)+nums[i]);
        }
        List<Map.Entry<Integer,Integer>> l=new ArrayList<Map.Entry<Integer,Integer>>(sum.entrySet());
        Collections.sort(l,new Comparator<Map.Entry<Integer,Integer>>(){
            public int compare(Map.Entry<Integer,Integer> a,Map.Entry<Integer,Integer> b){
                if(a.getValue()<b.getValue()){
                    return -1;
                }
                else if(a.getValue()==b.getValue()){
                    return 0;
                }
                else{
                    return 1;
                }
            }
        });
        if(l.size()==1){//原数组中只有一个元素的情况
            return new int[2];
        }
        int min=Math.abs(l.get(1).getValue()-l.get(0).getValue());
        int left=Math.min(l.get(0).getKey(),l.get(1).getKey())+1;
        int right=Math.max(l.get(0).getKey(),l.get(1).getKey());
        for(int i=2;i<l.size();i++){
            if(Math.abs(l.get(i).getValue()-l.get(i-1).getValue())<min){
                min=Math.abs(l.get(i).getValue()-l.get(i-1).getValue());
                left=Math.min(l.get(i).getKey(),l.get(i-1).getKey())+1;
                right=Math.max(l.get(i).getKey(),l.get(i-1).getKey());
            }
        }
        int[] res=new int[2];
        res[0]=left;
        res[1]=right;
        return res;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值