lintCode之最长连续序列
public int longestConsecutive(int[] num) { Map<Integer, Integer> map = new HashMap<Integer, Integer>(); int max = -1; int length = 0; for (int i : num){ if (map.get(i + 1) != null && map.get(i - 1) != null){ length = map.get(i + 1) - map.get(i - 1); int temp = map.get(i - 1); map.put(map.get(i - 1), map.get(i + 1)); map.put(map.get(i + 1), temp); } else if (map.get(i + 1) != null){ map.put(i, map.get(i + 1)); map.put(map.get(i + 1), i); length = map.get(i) - i; } else if (map.get(i - 1) != null){ map.put(i, map.get(i - 1)); map.put(map.get(i - 1), i); length = i - map.get(i); } else if (map.get(i) == null){ map.put(i, i); } max = max > length ? max : length; } return max + 1; }
大体思路就是用Map的Key作为数轴 Value作为这一段连续序列的另一个端点
比方说 现在Map中有(1,1)和[(3,3)两个值 代表两段长度为1的序列
现在加入一个2 就会变成(1,3)和(3,1) 代表长度为3的一个序列
不断拼接得到一个最长的序列 就是结果 因为只需要遍历一遍 时间复杂度为O(n)