Lintcode-the nearest 0 sub-array and

Source: Internet
Author: User
Tags diff lintcode

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.