public List<List<Integer>> threeSum(int[] nums) { Arrays.sort(nums); List<List<Integer>> res = newArrayList<>(); for (inti=0; i < nums.length - 2; i++) { if (i > 0 && nums[i] == nums[i - 1]) continue; intleft= i + 1, right = nums.length - 1; while (left < right) { intsum= nums[i] + nums[left] + nums[right]; if (sum == 0) { res.add(Arrays.asList(nums[i], nums[left], nums[right])); while (left < right && nums[left] == nums[left + 1]) left++; while (left < right && nums[right] == nums[right - 1]) right--; left++; right--; } elseif (sum < 0) left++; else right--; } } return res; }
三、快慢指针
3.1 检测链表环
publicbooleanhasCycle(ListNode head) { ListNodeslow= head, fast = head; while (fast != null && fast.next != null) { slow = slow.next; fast = fast.next.next; if (slow == fast) returntrue; } returnfalse; }
3.2 找环入口
public ListNode detectCycle(ListNode head) { ListNodeslow= head, fast = head; while (fast != null && fast.next != null) { slow = slow.next; fast = fast.next.next; if (slow == fast) break; } if (fast == null || fast.next == null) returnnull; slow = head; while (slow != fast) { slow = slow.next; fast = fast.next; } return slow; }
四、滑动窗口
4.1 固定窗口大小
publicdouble[] findAverages(int[] nums, int k) { double[] res = newdouble[nums.length - k + 1]; doublesum=0; for (inti=0; i < nums.length; i++) { sum += nums[i]; if (i >= k - 1) { res[i - k + 1] = sum / k; sum -= nums[i - k + 1]; } } return res; }
4.2 可变窗口 - 最小覆盖子串
public String minWindow(String s, String t) { int[] need = newint[128]; for (char c : t.toCharArray()) need[c]++; intleft=0, right = 0; intcount= t.length(); intminLen= Integer.MAX_VALUE; intstart=0; while (right < s.length()) { charc= s.charAt(right); if (need[c] > 0) count--; need[c]--; right++; while (count == 0) { if (right - left < minLen) { minLen = right - left; start = left; } charlc= s.charAt(left); need[lc]++; if (need[lc] > 0) count++; left++; } } return minLen == Integer.MAX_VALUE ? "" : s.substring(start, start + minLen); }
4.3 最长无重复子串
publicintlengthOfLongestSubstring(String s) { int[] index = newint[128]; intleft=0, maxLen = 0; for (intright=0; right < s.length(); right++) { charc= s.charAt(right); left = Math.max(left, index[c]); maxLen = Math.max(maxLen, right - left + 1); index[c] = right + 1; } return maxLen; }