原始题目:
给定一个无序的整数序列, 找到最长的连续子序列。
例如:
给定[100, 4, 200, 1, 3, 2],
最长的连续子序列是[1, 2, 3, 4]。
第一种解法:不要求时间复杂度,直接排序后比较得到最长子序列。
第二种解法:要求时间复杂度,用HashSet的空间换时间。先将元素全部放入HashSet中,然后从第一个元素开始,取出,找x-1是否在set里, 若在 就 跳出,判断下一个元素(因为若x-1在set中,我们从当前的元素开始寻找连续子序列是无意义的,因为找到的子序列也不会是最长的,我们必须 从 当前元素的上一个元素不在set中开始向后寻找子序列),不在就找x+1,x+2...是否在set里,直到x+i不在set中,算出子序列长度,与最长的进行比较。
import java.util.HashSet;
/**
* Longest Consecutive Sequence
*
* Given an unsorted array of integers, find the length of the longest
* consecutive elements sequence.
*
* For eample, Given [100, 4, 200, 1, 3, 2], The longest consecutive elements
* sequence is [1, 2, 3, 4]. Return its length: 4.
*
* Your algorithm should run in O(n) complexity.
*
*/
public class LongestConsecutiveSequence {
public static void main(String args[]){
int arr[]={100,4,200,1,3,2};
System.out.println(find2(arr));
// for(int i=0;i<arr.length;i++)
// System.out.println(arr[i]);
}
/*如果不要求o(n)时间复杂度 直接排序后比较得到最长子序列*/
public static int find1(int arr[]){
sort(arr,0,arr.length-1);
int max=1;
int temp=1;
for(int i=0;i<arr.length-1;i++){
if(arr[i+1]==arr[i]+1){
temp++;
System.out.println(temp+"aa");
}
else{
max=Math.max(max, temp);
temp=1;
}
}
max=Math.max(max, temp);
return max;
}
/*快排*/
public static void sort(int arr[],int left,int right){
if(left<right){
int mid=partition(arr,left,right);
sort(arr,left,mid-1);
sort(arr,mid+1,right);
}
}
public static int partition(int arr[],int left,int right){
int pointKey=arr[left];
while(left<right){
while(arr[right]>pointKey&&left<right){
right--;
}
arr[left]=arr[right];
while(arr[left]<pointKey&&left<right){
left++;
}
arr[right]=arr[left];
}
arr[left]=pointKey;
return left;
}
/*要求在o(n)时间复杂度 用hashSet 空间换时间*/
public static int find2(int []arr){
HashSet<Integer> set=new HashSet<>();
int max=1;
for(int array:arr){
set.add(array);
}
for(int array:arr){
if(set.contains(array-1)){//array-1在set里面,直接跳出,开始下一次遍历
continue;
}
else {
int temp=array;
while(set.contains(temp)){
set.remove(temp);//找到一个就从set中移除一个,这样后续的set在查找时效率会提高
temp++;
}
// while(set.remove(temp++));//加分号表示没有循环语句
if(temp!=array){
max=Math.max(max, temp-array);
System.out.println("max"+max);
}
}
}
return max;
}
}