题意:

image.png

解题思路:

  1. 思路:时间复杂度主要是排序,O(nlgn);空间复杂度O(1)
  2. 1. 排序,得到连续序列的数字;
  3. 2. 从前往后扫描一遍数组,记录差值为1的最大长度;
  4. 3. 当差值不为1的时候,更新最大长度,然后以下一个元素为起点,重新计算长度;

PHP代码实现:

  1. class Solution {
  2. function longestConsecutive($nums) {
  3. // return $this->longestConsecutive1($nums);
  4. if (count($nums) == 0) return 0;
  5. sort($nums);
  6. $res = 1;
  7. $curStreak = 1;
  8. for ($i = 1; $i < count($nums); $i++) {
  9. if ($nums[$i] != $nums[$i - 1]) {
  10. if ($nums[$i] == $nums[$i - 1] + 1) {
  11. ++$curStreak;
  12. } else {
  13. $res = max($res, $curStreak);
  14. $curStreak = 1;
  15. }
  16. }
  17. }
  18. return max($res, $curStreak);
  19. }
  20. function longestConsecutive1($nums) {
  21. if (empty($nums) || count($nums) == 0) return 0;
  22. sort($nums);
  23. $max = $p = 0;
  24. while ($p < count($nums)) {
  25. $len = 1;
  26. while ($p < count($nums) - 1) {
  27. if ($nums[$p + 1] - $nums[$p] > 1) break;
  28. if ($nums[$p + 1] - $nums[$p] == 1) ++$len;
  29. ++$p;
  30. }
  31. $max = max($max, $len);
  32. ++$p;
  33. }
  34. return $max;
  35. }
  36. function longestConsecutive2($nums) {
  37. if (count($nums) == 0) return 0;
  38. $res = 0;
  39. foreach($nums as $num) {
  40. $curNum = $num;
  41. $curStreak = 1;
  42. while ($this->arrayContains($nums, $curNum + 1)) {
  43. ++$curNum;
  44. ++$curStreak;
  45. }
  46. $res = max($res, $curStreak);
  47. }
  48. return $res;
  49. }
  50. function arrayContains($arr, $num) {
  51. //return in_array($num, $arr);
  52. for ($i = 0; $i < count($arr); $i ++) {
  53. if ($arr[$i] == $num) return true;
  54. }
  55. return false;
  56. }
  57. }

GO代码实现:

  1. func longestConsecutive(nums []int) int {
  2. if len(nums) == 0 {
  3. return 0
  4. }
  5. sort.Ints(nums)
  6. res, curStreak := 1, 1
  7. for i := 1; i < len(nums); i++ {
  8. if nums[i-1] == nums[i] {
  9. continue
  10. }
  11. if nums[i-1] + 1 == nums[i] {
  12. curStreak++
  13. } else {
  14. curStreak = 1
  15. }
  16. if curStreak > res {
  17. res = curStreak
  18. }
  19. }
  20. return res
  21. }