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
return
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; */
相关文章推荐
- LintCode : 最接近零的子数组和 Subarray Sum Closest
- Subarray Sum Closest
- **[Lintcode]Subarray Sum Closest最接近零的子数组和
- LintCode-Subarray Sum Closest
- [LintCode] Subarray Sum Closest
- Lintcode139 Subarray Sum Closest solution 题解
- Lintcode: Subarray Sum Closest
- LintCode 139. Subarray Sum Closest
- LintCode Subarray Sum Closest
- [刷题]Subarray Sum Closest
- lintcode-medium-Subarray Sum Closest
- Subarray Sum Closest
- lintcode:Subarray Sum Closest
- [LintCode]Subarray Sum Closest
- Subarray Sum Closest
- Subarray Sum Closest
- 139. Subarray Sum Closest
- #139 Subarray Sum Closest
- lintcode: Subarray Sum Closest
- Subarray Sum Closest