这道题的思路就是把不同的元素的 index 组成 Pair,这样做的好处就是,将来 sort 这些 Pair 的和,找到最相近的两个,然后他们就是 closest 了。
publicclassSolution {publicclassPair {int sum;int index;publicPair(int sum,int index) {this.sum= sum;this.index= index; } } /** * @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 */publicint[] subarraySumClosest(int[] nums) {int[] res =newint[2];if (nums ==null||nums.length==0) {return res; }int len =nums.length;if (len ==1) { res[0] = res[1] =0;return res; }Pair[] sums =newPair[len +1];int prev =0; sums[0] =newPair(0,0);for (int i =1; i <= len; i++) { sums[i] =newPair(prev + nums[i -1], i); prev = sums[i].sum; }Arrays.sort(sums,newComparator<Pair>() {publicintcompare(Pair a,Pair b) {returna.sum-b.sum; } });int ans =Integer.MAX_VALUE;for (int i =1; i <= len; i++) {if (ans > sums[i].sum- sums[i -1].sum) { ans = sums[i].sum- sums[i -1].sum;int[] temp =newint[] {sums[i].index-1, sums[i -1].index-1};Arrays.sort(temp); res[0] = temp[0] +1; res[1] = temp[1]; } }return res; }}