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]
.
使用排序算法进行处理
java
class Pair {
int index;
int sum;
public Pair(int index, int sum) {
this.index = index;
this.sum = sum;
}
}
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
if (nums == null || nums.length == 0) {
return new int[]{};
}
int[] arr = new int[2];
if (nums.length == 1) {
arr[0] = arr[1] = 0;
return arr;
}
Pair[] p = new Pair[nums.length + 1];
p[0] = new Pair(0, 0);
for (int i = 1; i < p.length; i++) {
p[i] = new Pair(i, p[i - 1].sum + nums[i - 1]);
}
Comparator<Pair> cmp = new Comparator<Pair>() {
public int compare(Pair a, Pair b) {
return a.sum - b.sum;
}
};
Arrays.sort(p, cmp);
int min = Integer.MAX_VALUE;
for (int i = 1; i < p.length; i++) {
if (min > p[i].sum - p[i - 1].sum) {
min = p[i].sum - p[i - 1].sum;
arr[0] = p[i - 1].index - 1;
arr[1] = p[i].index - 1;
}
}
Arrays.sort(arr);
arr[0]++;
return arr;
}
}