给定一个整数数组,找到一个和最接近于零的子数组。返回第一个和最有一个指数。你的代码应该返回满足要求的子数组的起始位置和结束位置
给出[-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;
}
}