leetcode之longest-consecutive-sequence

问题描述:
Given an unsorted array of integers, find the length of the longest consecutive elements sequence.

For example,
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.

题目要求算法时间复杂度是O(n),所以先排序的思想是行不通的,这里为了做比较,也实现了先排序的方法。
另一种算法的思想就是用空间换时间:
采用hash表,先初始化一个hash表, 存储所有数组元素, 然后遍历这个数组, 对找到的数组元素, 去搜索其相连的上下两个元素是否在hash表中, 如果在, 删除相应元素并增加此次查找的数据长度, 如果不在, 从下一个元素出发查找。

package suda.alex.leetcode;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;

public class LongestConsecutive {

    /**
     * @param args
     */
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("input the size of num:");
        int len = scanner.nextInt();
        System.out.println("input num:");
        int[] num = new int[len];
        for (int i = 0; i < len; i++) {
            num[i] = scanner.nextInt();
        }
        System.out.println("the longestConsecutive num is:"
                + longestConsecutive2(num));

    }

    public static int longestConsecutive1(int[] num) {
        int len = num.length;
        if (len == 0) {
            return 0;
        }
        Arrays.sort(num);
        int count = 1;
        int maxLen = 1;
        for (int i = 1; i < len; i++) {
            if (num[i] == num[i - 1] + 1) {
                count++;
            } else {
                if (num[i] != num[i - 1]) {
                    count = 1;
                }
            }
            if (count > maxLen) {
                maxLen = count;
            }
        }
        return maxLen;
    }

    public static int longestConsecutive2(int[] num) {
        int len = num.length;
        if (len == 0) {
            return 0;
        }
        Set<Integer> set = new HashSet<Integer>();
        int maxLen = 1;
        for (int i = 0; i < len; i++) {
            set.add(num[i]);
        }
        for (int i = 0; i < len; i++) {
            int count = 1;
            int leftNum = num[i] - 1;
            int rightNum = num[i] + 1;
            while (set.contains(leftNum)) {
                count++;
                set.remove(leftNum);
                leftNum--;
            }
            while (set.contains(rightNum)) {
                count++;
                set.remove(rightNum);
                rightNum++;
            }
            if(count > maxLen){
                maxLen = count;
            }
        }
        return maxLen;
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值