您的位置:首页 > 其它

LintCode:最接近零的子数组和

2016-01-27 16:54 441 查看
给定一个整数数组,找到一个和最接近于零的子数组。返回第一个和最有一个指数。你的代码应该返回满足要求的子数组的起始位置和结束位置
您在真实的面试中是否遇到过这个题?

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;

}
}



内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: