Given an integer array, find a subarray with sum closest to zero. Return the indexes of the first number and last number.
Example
Given [-3, 1, 1, -3, 5]
, return [0, 2]
, [1, 3]
, [1, 1]
, [2, 2]
or [0, 4]
.
Challenge
O (NLOGN) time
Public classSolution {/** * @paramnums: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[2]; int[] res =New int[2]; if(Nums.length = = 1) {res[0] = 0; res[1] = 0; returnRes; } node[] Nodes=NewNode[nums.length]; intsum = 0; for(inti = 0; i < nums.length; i++) {sum+=Nums[i]; Nodes[i]=Newnode (i, sum); } arrays.sort (Nodes,NewComparator<node>(){ Public intCompare (node n1, node N2) {returnN1.sum-n2.sum; } }); intindex = 0; intdiff = nodes[index + 1].sum-nodes[index].sum; for(inti = 0; i < nums.length-1; i++){ if(Nodes[i + 1].sum-nodes[i].sum <diff) {Index=i; Diff= Nodes[i + 1].sum-nodes[i].sum; }} res[0] = math.min (nodes[index].index, Nodes[index + 1].index) + 1; res[1] = Math.max (Nodes[index].index, Nodes[index + 1].index); returnRes; } classnode{intindex; intsum; PublicNodeintIndexintsum) { This. index =index; This. sum =sum; } } }
Lintcode-medium-subarray Sum Closest