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

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

664

被折叠的 条评论
为什么被折叠?



