您的位置:首页 > 其它

Continuous Subarray Sum II

2015-09-01 10:35 375 查看
Given an integer array, find a continuous rotate subarray where the sum of numbers is the biggest. Your code should return the index of the first number and the index of the last number. (If their are duplicate answer, return anyone. The answer can be rorate
array or non- rorate array)

Have you met this question in a real interview? 

Yes

Example

Give 
[3, 1, -100,
-3, 4]
, return 
[4,1]
.
这题与Continuous Subarray Sum的区别在与,由于变成了环,这样起点就是不确定了的,所以问题变成了如何找起点能够使得环得到最大的联系字串和;说先想到的是暴力解,遍历所有的可能的起点,然后得到最大值的起点,再按照Continuous Subarray Sum的方式求解起始点位置,这样的时间复杂度为O(N^2);那么如何优化,让其可以达到O(N)的时间复杂度;这里要用到连续最小子串的概念,如果可以求出在原数组中,连续最小字串的最后一个点的下标值为minIndex,假如,以minIndex前的点为起点,由于其要经过最小字串区间,所以其值必然不会达到最终的最大,因此,要使字串能够尽可能的大,那么其起点应该从minIndex开始;有了这样的分析之后代码自然就好写了。
class Solution {
public:
/**
* @param A an integer array
* @return A list of integers includes the index of
* the first number and the index of the last number
*/
vector<int> continuousSubarraySumII(vector<int>& A) {
// Write your code here
vector<int> ans;
int len = A.size();
if(len < 1)
return ans;
if(len == 1)
{
ans.push_back(0);
ans.push_back(0);
return ans;
}

int Min = INT_MAX, minIndex = 0, curMin = A[0];
for(int i = 1; i < len; ++i)
{
curMin = min(curMin + A[i], A[i]);
if(curMin < Min)
{
Min = curMin;
minIndex = i;
}
}

int index = (minIndex + 1) % len, Max = Min, high = minIndex, curMax = Min;
while(index != minIndex)
{
curMax = max(curMax + A[index], A[index]);
if(Max < curMax)
{
Max = curMax;
high = index;
}
index = (index + 1) % len;
}

int low = high, tmpMax = Max;
while(tmpMax)
{
tmpMax -= A[low];
low = (low - 1 + len) % len;
}

ans.push_back((low + 1) % len);
ans.push_back(high);
return ans;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Continuous Subarray