您的位置:首页 > 其它

139. Subarray Sum Closest

2017-11-16 20:54 375 查看
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 Pairs {
int index;
int sum;
public Pairs(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
int[] arr = new int[2];
if (nums == null || nums.length == 0) {
return arr;
}
if (nums.length == 1) {
arr[0] = arr[1] = 0;
return arr;
}
Pairs[] p = new Pairs[nums.length + 1];
p[0] = new Pairs(0, 0);
for (int i = 1; i <= nums.length; i++) {
p[i] = new Pairs(i, p[i - 1].sum + nums[i - 1]);
}
Comparator<Pairs> cmp = new Comparator() {
public int compare(Object a, Object b) {
return ((Pairs)a).sum - ((Pairs)b).sum;
}
};
Arrays.sort(p, cmp);
int max = Integer.MAX_VALUE;
for (int i = 1; i <= nums.length; i++) {
if (max > p[i].sum - p[i - 1].sum) {
max = p[i].sum - p[i - 1].sum;
arr[0] = p[i].index - 1;
arr[1] = p[i - 1].index - 1;
Arrays.sort(arr);
}
}
arr[0]++;
return arr;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: