given an array of integers, find a sub-array that is closest to zero. Returns the first and most of the indices. your code should return the starting and ending positions of the subarray that meet the requirements
Sample Example
Given [ -3, 1, 1, -3, 5], return [0, 2],[1, 3], [1, 1], [2, 2] or [0, 4]
challenges
O (NLOGN) Time complexity
Analysis: First O (n^2) algorithm is very good to think, the direct lifting point on the line, see the complexity of the challenge, want to be sure to sort or two points what, here did not find the nature of the two points, so want to only want to sort, we know that continuous array and is actually the difference between the prefix and the most close to 0 Two prefixes and to the nearest, then the direct prefix and sorting, two adjacent comparisons can be
Code:
Class Solution {public:/** * @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 */vector<int> subarraysumclosest (vector <int> nums) {//write your code here vector<pair<int,int> > sum; int temp = 0; Sum.push_back (Make_pair (temp,-1)); for (int i=0;i<nums.size (); i++) {temp+=nums[i]; Sum.push_back (Make_pair (temp,i)); } sort (Sum.begin (), Sum.end ()); int start,end; int diff = Int_max; for (int i=1;i<sum.size (); i++) {if (ABS (Sum[i].first-sum[i-1].first) <=diff) { diff = ABS (sum[i].first-sum[i-1].first); start = min (sum[i].second,sum[i-1].second) +1; end = Max (Sum[i].second,sum[i-1].second); }} vector<int> ret; Ret.push_back (start);Ret.push_back (end); return ret; }};
Lintcode-the nearest 0 sub-array and