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? YesExampleGiven [-3, 1, 1, -3, 5], return [0, 2], [1, 3], [1, 1], [2, 2] or [0, 4].ChallengeO(nlogn) time
Analysis:
s[i+1] = nums[0]+....nums[i], also record the index i into s[i+1]. Sort array s, and the minimum difference between two consecutive element, is the the subarray.
1 class Element implements Comparable{ 2 int index; 3 int value; 4 public Element(int index, int value) { 5 this.index = index; 6 this.value = value; 7 } 8 9 public int compareTo(Element other) {10 return this.value - other.value;11 }12 13 public int getIndex() {14 return index;15 }16 17 public int getValue() {18 return value;19 }20 } 21 22 23 24 25 public class Solution {26 /**27 * @param nums: A list of integers28 * @return: A list of integers includes the index of the first number 29 * and the index of the last number30 */31 32 public int[] subarraySumClosest(int[] nums) {33 // write your code here34 int[] res = new int[2];35 Element[] sums = new Element[nums.length+1];36 sums[0] = new Element(-1, 0);37 int sum = 0;38 for (int i=0; i