无序数组中找到最长连续子序列
来源:互联网 发布:韩版硅胶手表淘宝 编辑:程序博客网 时间:2024/05/22 13:55
原始题目:
给定一个无序的整数序列, 找到最长的连续子序列。
例如:
给定[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;}}
0 0
- 无序数组中找到最长连续子序列
- 无序数组中最长连续序列
- 一个无序整数数组中找到最长连续序列(Longest Consecutive Sequence)和两个元素使得相差最小
- 无序整形数组,如何找到最长连续序列长度,时间复杂度O(n)
- 无序数组的最长递增子序列
- 找出无序数组的最长连续子数组
- 求数组中最长的连续子序列
- 求数组中最长连续递增子序列
- O(n)时间找出无序数组中最长的连续递增序列
- 无序数组中最长非降子序列长度
- 数组中最长连续序列
- 矩阵中最长连续递增子序列
- 连续最长子序列
- 最长连续子序列
- 最长连续子序列
- 最长连续子序列
- 最长连续子数组
- 在一个乱序的数组中找到最长的递增子序列
- php面试常用题目精解(一)
- 记录一些android的基础知识
- PHP面向对象编程设计模式(三)工厂模式
- JavaScript中的setTimeout()和setInterval()
- VS + wxWidgets开发配置指南
- 无序数组中找到最长连续子序列
- Android 配置Freeline教程
- 读书笔记(二)---看看LayoutInflater的源码
- QT调用OpenCV编译产生的“ACCESS_MASK”问题
- listview的二级优化
- IOS 根据对象属性值过滤数组中的元素 Filter NSMutableArray with object property
- Java基础知识小结_运算符优先级
- 简单代理模式与策略模式区别
- 实验报告:2:2