Title Description
There are an array of integers, write a function to find out the index m and n, as long as the elements between m and n are sorted, the entire array is ordered. Note: nm should be as small as possible, that is to say, find the shortest sequence of qualifying.
Int size n of a given array A and the array, return a tuple representing the required start and end sequence. (Prosequence from zero reference position, if the original sequence of ordered to return to [0,0]). A guarantee of the elements are positive integers.
Test sample:
[1,4,6,5,9,10],6
Returns: [2,3]
Stupid way
class Rearrange {
public:
vector<int> findSegment(vector<int> A, int n) {
// write code here
vector<int> res(2, 0);
vector<int> temp(A.begin(), A.end());
sort(A.begin(), A.end());
for(int i = 0; i < n; ++i)
{
if(temp[i] != A[i])
{
res[0] = i;
break;
}
}
for(int i = n - 1; i >= 0; --i)
{
if(temp[i] != A[i])
{
res[1] = i;
return res;
}
}
return res;
}
};
Traversed twice, once from left to right to find N, once from right to left to find M
(1) from left to right to find N
If the largest element preceding the current element is smaller than the current element shall be described in [the MN] and random sequence at the current element is the greatest subject to random element N so that the update superscript current element.
(2) from right to left to find M
If the current is greater than the smallest element before the element is the current element shall be described in [the MN] and random sequence at the current element is the current minimum elements so that the update target disorder current element index M
class Rearrange {
public:
vector<int> findSegment(vector<int> A, int n) {
// write code here
vector<int> res(2, 0);
int max = A[0];
int min = A[A.size() - 1];
for(int i = 0; i < n; ++i)
{
if(A[i] >= max)
{
max = A[i];
}
else
{
res[1] = i;
}
}
for(int i = n - 1; i >= 0; --i)
{
if(A[i] <= min)
{
min = A[i];
}
else
{
res[0] = i;
}
}
return res;
}
};