=========数组========
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; } }