Leetcode 128:Longest Consecutive Sequence

超开心,第一次自己写出了Leetcode里面hard难度中beats 100%的答案,不过……我觉得可能有点小问题。下面说。

Description:

Given an unsorted array of integers, find the length of the longest consecutive elements sequence.

Your algorithm should run in O(n) complexity.

Example:

Input: [100, 4, 200, 1, 3, 2]
Output: 4
Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4.
Solution:

1. 我的代码:AC且beats 100%。但是!Arrays.sort()方法的平均复杂度是O(nlogn),而题目要求是O(n)。所以,尽管对于题目给出的测试用例AC且速度很快,严格意义上,这只是个作弊又凑巧跑出了好结果的答案。
import java.util.*;
class Solution {
    public int longestConsecutive(int[] nums) {
        Arrays.sort(nums);  //先排序
        int count = 0;
        int temp = 0;
        if(nums == null||nums.length == 0) //对于没有输入的这种情况,返回值应该是0
            count = 0;
        else if(nums.length == 1) //对于只有一个输入的这种情况,返回值是1
            count = 1;
        else{    //对于普遍的情况       
            temp = 1;
            int i = 0;
            while(i < nums.length - 1){
                if(nums[i + 1] - nums[i] == 1){  //最正常递增的情况
                    temp++;
                    i++;
                    if(temp > count)
                    	count = temp;
                }
                else if(nums[i + 1] - nums[i] == 0){  //有相等值的情况
                    i++;
                    if(temp > count)
                    	count = temp;
                }
                else{  //跳出递增的处理
                    if(temp > count)
                    	count = temp;
                    i++;
                    temp = 1;
                }
            }
        }
        return count;
    }
}


2.  正确的代码:真正实现O(n)的应该是采用HashMap。用了有点类似于动态规划的思想。
public int longestConsecutive(int[] num) {
    int res = 0; //用来记录最后结果,也就是迄今为止,连续最大的个数 
    HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
    for (int n : num) { //foreach语句,n是num中每个元素
        if (!map.containsKey(n)) {
        	//left是指比n小的连续数目,也就是key=n-1的value值
            int left = (map.containsKey(n - 1)) ? map.get(n - 1) : 0;
            //right是指比n大的连续数目,也就是key=n+1的value值
            int right = (map.containsKey(n + 1)) ? map.get(n + 1) : 0;
            // sum: length of the sequence n is in
            //n的value值就是比n小的部分连续数目加上比n大的连续数目加它自己的一个
            int sum = left + right + 1;
            map.put(n, sum); //将n作为key,将sum作为value放入HashMap中
            
            // keep track of the max length 
            res = Math.max(res, sum); //更新现有最大连续数目
            
            // extend the length to the boundary(s)
            // of the sequence
            // will do nothing if n has no neighbors
            // 要更新现有最长序列的key的最小值(n-left)和最大值(key+right)对应的value值
            map.put(n - left, sum);
            map.put(n + right, sum);
        }
        else {
            // duplicates
        	//如果HashMap中已经有个对应的key值,直接开始下一次循环,也就是跳过它,对下一个元素进行处理
            continue;
        }
    }
    return res;
}


 
 


猜你喜欢

转载自blog.csdn.net/weixin_41876155/article/details/80210034