Update Leetcode to solve Java answers on a regular basis.
Choose a topic using pick one.
The title means to find the length of the longest ordered continuous array, given an unordered array.
The idea is to assume that the input array's number range is between -10000~10000, create an array of 2w space, assign a value of 0, traverse the given array, treat the array value as an array subscript, create an array corresponding to the value +1, and finally iterate over the created array to get the maximum length.
The code is as follows:
1 Public classSolution {2 Public intLongestconsecutive (int[] nums) {3 int[] Count =New int[20000];4 for(inti = 0; I < 20000; i++)5Count[i] = 0;6 for(inti = 0; i < nums.length; i++)7Count[nums[i] + 10000]++;8 9 intMax = 0;Ten intTMP = 0; One for(inti = 0; I < 20000; i++){ A if(count[i]! = 0) -tmp++; - Else{ themax = tmp > Max?Tmp:max; -TMP = 0; - } - } + - returnMax; + } A}
Theoretically speaking, the idea is feasible, but the individual joins the restriction condition, that is the input in -10000~10000, a test case will this idea to fight excrement.
In the hint, you want to use the union Find method to answer the question. Data structure did not study hard, looked at the half-day did not understand, first lazy take a simple method to deal with. The idea is to sort the array and then count the longest consecutive subsequence. The logic is simple, although the problem is added to the limit, the time complexity in O (n), but the specific test did not limit this, and the results are unexpectedly fast. The code is as follows:
1 Public classSolution {2 Public intLongestconsecutive (int[] nums) {3 Arrays.sort (nums);4 intmax = 1;5 intTMP = 1;6 for(inti = 1; I <= nums.length; i++){7max = tmp > Max?Tmp:max;8 if(i = =nums.length)9 Break;Ten if(Nums[i] = = Nums[i-1]){} One Else if(Nums[i]-nums[i-1] = = 1) Atmp++; - Else -TMP = 1; the } - - returnMax; - } +}
Take the time to understand the Union Find method and then add a note to the subject.
Leetcode 128. Longest consecutive Sequence