[LeetCode] 无序数组中的最长连续数列 The Longest Consecutive Sequence in an unsorted array

[LeetCode] 无序数组中的最长连续数列 The Longest Consecutive Sequence in an unsorted array

给你一个无序的数组,{5, 7, 3, 4, 9, 10, 1, 15, 1, 3, 12, 2, 11},那么最长的连续数列是{1, 2, 3, 4, 5}。

思路:

Dump everything to a hash set.

Now go through the hashset. For each element, look up the set for all values neighboring the current value. Keep track of the largest sequence you can find, while removing the elements found from the set. Save the count for comparison.

Repeat this until the hashset is empty.

Assuming lookup, insertion and deletion are O(1) time, this algorithm would be O(N) time.

伪代码如下:

int start, end, max
 int temp_start, temp_end, count

 hashset numbers

 for element in array:
     numbers.add(element)

 while !numbers.empty():
     number = numbers[0]
     count = 1
     temp_start, temp_end = number 

     while numbers.contains(number - 1):
         temp_start = number - 1; count++
         numbers.remove(number - 1)

     while numbers.contains(number + 1):
         temp_end = number + 1; count++
         numbers.remove(number + 1)

     if max < count:
         max = count
         start = temp_start; end = temp_end

 max_range = range(start, end)

代码如下:

#include<stdio.h>
#include<stdlib.h>
#include<iostream>
#include <set>
#include <string.h>

using namespace std;

int LCS(int arr[], int n)
{
	set<int> arr_set (arr, arr+n);

	int maxCount = 0, // length of the longest consecutive subsequence
		left_range = 0, // start of LCS
		 right_range = 0; // end of LCS
	while(!arr_set.empty()){
		// each time, retrieve the first element in the set
		set<int>::iterator iter = arr_set.begin();
		int val = *iter-1;
		int left = *iter, right = *iter;
		int count = 1;

		// find out the neighboring numbers less than *iter
		while(arr_set.find(val)!=arr_set.end())
		{
			count++;
			left--;
			arr_set.erase(val);
			val--;
		}

		// find out the neighboring numbers greater than *iter
		val = *iter+1;
		while(arr_set.find(val)!=arr_set.end())
		{
			count++;
			right++;
			arr_set.erase(val);
			val++;
		}
	
		// update if necessary	
		if(count>maxCount)
		{
			maxCount = count;
			left_range = left;
			right_range = right;
		}
		
		arr_set.erase(*iter);
	}

	cout<<left_range<<"|"<<right_range<<endl;
	return maxCount;
}

		


int main()
{
	int arr[] = {5, 7, 3, 4, 9, 10, 1, 15, 1, 3, 12, 2, 11};
	int a = LCS(arr, sizeof(arr)/sizeof(int));
	cout<<a;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值