【topic】
The length of a given array arr, AIM and an integer, in seeking arr, the cumulative sum is equal to the longest num subarray
example:
arr = { 7,3,2,1,1,7,7,7 } aim = 7
There are many sub-array cumulative sum is equal to 7, but the longest subarray is {3,2,1,1}, it returns to its length 4
[Solving]
Using the map, the number of the array from the first accumulation start, recording and accumulating a first position to a certain value
The initial map data storage <0, -1> as there is no accumulation of a number and is set to 0, the position of the digital array - the array position [i.e., non-traversing]
map <sum, index>, when the sum unchanged, map does not update! ! !
note:
We're looking for sum - aim = index == key first appeared in the map of the location, and records
For example:? 7 3 2 1 1 7 - 6 - 1 7 num == 7
The cumulative numbers of 0 7, sum = 7, sum - aim = 0, map the present position key = 0, the position of the earliest - 1,
DESCRIPTION able to form a sub-array, and so that the accumulation of AIM, the array length of 0 - (- 1) = 1
Then continue to traverse backwards when traversing to the fourth digit 1,
map记录为{ <0,-1><7,0><10,1><12,2><13,3><14,4> },
At this sum is 14, sum - aim = 14 - 7 = 7, key = 7 present the map, the position of the first occurrence is 0,
DESCRIPTION able to form a sub-array, and so that the accumulation of AIM, the array length of 4 - (0) = 4
[Code]
. 1 #pragma Once 2 #include <the iostream> . 3 #include <Map> . 4 #include <Vector> . 5 . 6 the using namespace STD; . 7 . 8 int mostLongSubArray (Vector < int > V, int AIM) . 9 { 10 int RES = 0 ; // record the longest recording . 11 Map < int , int > m; // record accumulation and 12 is m [ 0 ] = - . 1 ; // beginning position of the sum is zero 13 is int SUM = 0 ; 14 for ( int I = 0 ; I <v.size (); ++ I) 15 { 16 SUM = + V [I]; . 17 IF (m.find (SUM) == m.end ()) // accumulation and absence of 18 is m [SUM] = I; . 19 Auto m.find PTR = (SUM - AIM); 20 is IF ! (PTR = m.end ()) // record the presence of 21 is RES = RES > (I - (ptr-> SECOND)) RES:? (I - (ptr-> SECOND)); // update the longest recording subarray 22 is } 23 is return res; 24 } 25 26 void Test() 27 { 28 vector<int>v; 29 v = { 7,3,2,1,1,7,7,7 }; 30 cout << mostLongSubArray(v, 7) << endl; 31 v = { 7,3,2,1,1,7,-6,-1,7 }; 32 cout << mostLongSubArray(v, 7) << endl; 33 v = { 7,5,2,4,3,1,1,1,1,1,1,1,1,7 }; 34 cout << mostLongSubArray(v, 7) << endl; 35 }