=========数组========

1.如果题目要求O(n)复杂度,一般就需要考虑使用two pointer 或者sliding window或者HashMap、 HashSet

eg: https://leetcode.com/problems/longest-consecutive-sequence/description/ 就是利用HashSet ,巧妙将有序的数组转化为无序,就可以不用考虑顺序,直接看有没有每个数相邻的数就行:对每个数,以该数为中心,向左右扩张,直到不连续为止,记下最大长度。

public class LongestConsecutiveSequnce {

    public int longestConsecutive(int[] nums) {
        if (nums.length == 0) return 0;
        HashSet<Integer> set = new HashSet<>();
        for (int num : nums) set.add(num);
        int res = 0;
        for (int num : nums) {
            int tmpLongest = 1;
            for (int i = num + 1; set.contains(i); i++) {
                set.remove(i);
                tmpLongest ++;
            }
            for (int i = num - 1; set.contains(i); i--) {
                set.remove(i);
                tmpLongest ++;
            }
            res = Math.max(res, tmpLongest);
        }
        return res;
    }
}
View Code

相关文章:

  • 2021-05-28
  • 2021-08-04
  • 2021-09-26
  • 2021-05-10
  • 2021-08-30
  • 2021-05-04
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-07-26
  • 2022-12-23
  • 2021-08-05
  • 2021-06-03
  • 2022-02-09
相关资源
相似解决方案