LintCode:最接近零的子数组和

本文探讨如何在整数数组中找到一个和最接近于零的子数组,并提供了一个O(nlogn)时间复杂度的解题思路。通过排序和差分计算,找出满足条件的子数组边界。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

您在真实的面试中是否遇到过这个题?  
Yes
样例

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

挑战

O(nlogn)的时间复杂度 

标签   Expand  

相关题目   Expand 
解题思路:
可以先求出位置为i时候的num的0-i数组和sum,在按照大小排序。
排序后将sum相减,输出差最接近0的结果

public class Solution {
         class Pair {
          int sum;
          int index;
          public Pair(int sum, int index) {
               super();
               this.sum = sum;
               this.index = index;
          }

     }
    /**
     * @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
          int[] res = new int[2];
          if (nums.length == 0 || nums == null)
               return res;
          int len = nums.length;
          if (1 == len) {
               res[0] = 0;
               res[1] = 0;
               return res;
          }
          int pre = 0;
          Pair sumPair[] = new Pair[len + 1];
          sumPair[0] = new Pair(0, 0);
          for (int i = 1; i < len+1; i++) {
               sumPair[i] = new Pair(pre + nums[i - 1], i);
               pre = sumPair[i].sum;
          }
        Arrays.sort(sumPair, new Comparator<Pair>() {
           public int compare(Pair a, Pair b) {
               return a.sum - b.sum;
           }
        });
          int close = Integer.MAX_VALUE;
          for (int i = 1; i < len + 1; i++) {
               if(close>sumPair[i].sum-sumPair[i-1].sum){
                   close = sumPair[i].sum - sumPair[i-1].sum;
                    int tmp[] = new int[]{sumPair[i].index,sumPair[i-1].index};
                    Arrays.sort(tmp);
                    res[0] =  tmp[0];
                    res[1] =  tmp[1]-1;
               }
          }

          return res;

     }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值