最接近零的子数组和

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

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

1.子数组之和等于两个数组前序和之差,显然所有子数组之和等于全部数组前序和的排列组合
2.子数组和最接近0,即两个数组前序和相近,将数组前序和排序找出差值最小的两个相邻元素即可

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 class NSum{
        int n;
        int sum;
        public NSum(int n,int sum){
            this.n = n;
            this.sum = sum;
        }
    }
    public int[] subarraySumClosest(int[] nums) {
        // write your code here
        //检查参数
        if(nums.length < 2 || nums == null)
            return new int[]{0,0};

        NSum[] nSums= new NSum[nums.length + 1];
        nSums[0] = new NSum(0,0);
        int i = 0;
        //前缀和
        for(;i < nums.length;i++)
        {
            nSums[i + 1] = new NSum(i + 1,nSums[i].sum + nums[i]); 
        }

        int closeValue = Integer.MAX_VALUE;
        //对前缀和序列排序
        Arrays.sort(nSums, new Comparator<NSum>() {
            public int compare(NSum a, NSum b){
                return a.sum - b.sum;
            }
        });
        //求前缀和之差最小
        int[] result = new int[2];
        for (i = 1; i < nSums.length; i++){
            if (closeValue > (nSums[i].sum - nSums[i - 1].sum)){
                closeValue = nSums[i].sum - nSums[i - 1].sum;
                int[] temp = new int[]{nSums[i].n - 1, nSums[i - 1].n - 1};
                Arrays.sort(temp);
                result[0] = temp[0] + 1;
                result[1] = temp[1];
            }
        }
        return result;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值