您的位置:首页 > 其它

Subarray Sum Closest

2016-12-14 16:14 375 查看
Given an integer array, find a subarray with sum closest to zero. Return the indexes of the first number and last number.

Example

Given 
[-3, 1, 1, -3, 5]
,
return 
[0, 2]
[1,
3]
[1, 1]
[2,
2]
 or 
[0, 4]
.

class Pair {
int sum;
int index;
public Pair(int sum, int index) {
this.sum = sum;
this.index = 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
*/
public int[] subarraySumClosest(int[] nums) {
int[] result = new int[2];
if(nums == null || nums.length == 0) {
return result;
}
Pair[] list = new Pair[nums.length];
int prev = 0;
for(int i = 0; i < nums.length; i++) {
list[i] = new Pair(prev + nums[i], i);
prev += nums[i];
}
Arrays.sort(list, new Comparator<Pair>() {
public int compare(Pair a, Pair b) {
return a.sum - b.sum;
}
});
int diff = Integer.MAX_VALUE;
for(int i = 1; i < list.length; i++) {
if(diff > list[i].sum - list[i - 1].sum) {
diff = list[i].sum - list[i - 1].sum;
//set list[i - 1] as A, list[i] as B
//+ 1 because we don't need the cumulative sum from 0 to A
//but we want the cumulative sum from A to B
//so we should start from the right num of A
result[0] = Math.min(list[i].index, list[i - 1].index) + 1;
result[1] = Math.max(list[i].index, list[i - 1].index);
}
}
return result;
}
}

/**
*Pair stores the cumulative sum from 0 to i and the index i;
*/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  array