lintcode(139)最接近零的子数组和

Description:

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

Explanation:

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

Solution:

首先想到了遍历所有组合,但是超时了。然后借助定义新的类Pair存储和及序号。

将数组元素依次相加求和,并连同最后一位的index存入pair[]中。然后将pair[]按照sum的大小进行排序(从大到小)那么排序后相邻的两个sum值得差越小,说明从index1到index2之间元素的和越接近0。注意index大的一侧需要减一。

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
     */
    class Pair{
        int sum;
        int index;
        public Pair(int s , int i){
            this.index = i;
            this.sum = s;
        }
    }
    public int[] subarraySumClosest(int[] nums) {
        // write your code here
        int[] result = new int[]{0 , 0};
        if(nums == null || nums.length == 0 || nums.length == 1){
            return result;
        }
        
        int len = nums.length;
        Pair[] record = new Pair[len + 1];
        record[0] = new Pair(0 , 0);
        int prev = 0;
        for(int i = 1; i< len + 1;i++){
            prev += nums[i - 1];
            record[i] = new Pair(prev , i);
        }
        
        Arrays.sort(record , new Comparator<Pair>(){
            public int compare(Pair a , Pair b){
                return a.sum - b.sum;
            }
        });
        
        int min = Integer.MAX_VALUE;
        for(int i = 1;i<len + 1;i++){
            if(min > record[i].sum - record[i - 1].sum){
                min = record[i].sum - record[i - 1].sum;
                result[0] = Math.min(record[i].index , record[i - 1].index);
                result[1] = Math.max(record[i].index , record[i - 1].index) - 1;
            }
        }
        
        return result;
    }
}



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值