can be consolidated sub-arrays: After the order from small to large, the number of the following is 1 larger than the previous number, such as: [2,4,3,6,5] is an integrated array.
1 //getLiL.cpp: Defines the entry point of the console application. 2 //3 4#include"stdafx.h"5#include <iostream>6#include 7#include <iterator>8#include <Set>9 Ten using namespacestd; One A voidGetlil (int*arr,intlen) - { - if(arr = = NULL | | Len <=0) the return; - - intMinnum =0; - intMaxnum =0; + /*hash_set<int> MySet;*/ //Hash_set won't work. - Set<int>MySet; + intresult =0; A at - for(inti =0; I < len;i++) - { -Minnum =0x7fffffff; -Maxnum =0x80000000; - for(intj = I;i < len;j++) in { - Set<int>:: iterator ite; to if((Ite=myset.find (arr[j))! =myset.end ()) + Break; - //1. If there are duplicates in the array, it must not be consolidated and proceed directly the next time. the //using set to determine the time complexity of O (LOGN) * Myset.insert (Arr[j]); $ Panax Notoginseng //Each step calculates the current maximum minimum value, and each step is judged -Minnum =min (minnum,arr[j]); theMaxnum =Max (maxnum,arr[j]); + A if(Maxnum-minnum = = J-i) theresult = max (j-i +1, result); + //2. In a certain range, the difference of the maximum value is equal to the difference of the subscript, which can be integrated - } $ myset.clear (); $ } -cout<<result<<endl;//result = = 8 - } the - int_tmain (intARGC, _tchar*argv[])Wuyi { the intArr[] = {3,4,2,5,6,8, -,Ten, One, A, -, -, the, -}; -Getlil (arr, -); WuSystem"Pause"); - return 0; About}
View Code
The time complexity is O (n*n), which has the best time complexity without changing the elements of the array.
If you can change the structure of the array, you can directly take advantage of the sorting, Time complexity O (N*LOGN);
The longest-to-be-consolidated sub-array