您的位置:首页 > 其它

Subarray Sum Closest

2018-01-10 20:01 357 查看
Given an integer array, find a subarray with sum closest to zero. Return the indexes of the first number and last number.

Have you met this question in a real interview? 

Yes

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