一、数组

8) 双指针 ---- 滑动窗口

例题:

3. Longest Substring Without Repeating Characters

描述:Given a string, find the length of the longest substring without repeating characters.

题解:时间:92.67%,空间:87.02%

  1. public int lengthOfLongestSubstring(String s) {
  2. // check
  3. if(s == null || s.length() == 0) return 0;
  4.  
  5. // initial
  6. int[] freq = new int[256];
  7. Arrays.fill(freq, -1);
  8. int l = 0, r = 0, res = 0;
  9.  
  10. while(r < s.length()){
  11. if(freq[s.charAt(r)] != -1) l = Math.max(l, freq[s.charAt(r)] + 1);
  12. freq[s.charAt(r)] = r++;
  13. res = Math.max(res, r - l);
  14. }
  15.  
  16. return res;
  17. }

练习:

438. Find All Anagrams in a String

76. Minimum Window Substring

二、查找问题

1)查找有无:是否存在

2)查找对应关系:出现了几次

349. Intersection of Two Arrays   // 熟悉Set

描述:Given two arrays, write a function to compute their intersection.

  1. Input: nums1 = [1,2,2,1], nums2 = [2,2]
  2. Output: [2]
  1. public int[] intersection(int[] nums1, int[] nums2) {
  2. if(nums1 == null || nums1.length == 0 || nums2 == null || nums2.length == 0)
  3. return new int[0];
  4.  
  5. Set<Integer> set1 = new HashSet<Integer>();
  6. Set<Integer> setTemp = new HashSet<Integer>();
  7.  
  8. for(int num : nums1) set1.add(num);
  9. for(int num : nums2) if(set1.contains(num)) setTemp.add(num);
  10.  
  11. int k = setTemp.size();
  12. int[] res = new int[k];
  13. for(int num : setTemp) res[--k] = num;
  14.  
  15. return res;
  16. }

350. Intersection of Two Arrays II          // 熟悉 Map

描述:Given two arrays, write a function to compute their intersection.

  1. Input: nums1 = [1,2,2,1], nums2 = [2,2]
  2. Output: [2,2]
  1. public int[] intersect(int[] nums1, int[] nums2) {
  2. if(nums1 == null || nums1.length == 0 || nums2 == null || nums2.length == 0)
  3. return new int[0];
  4.  
  5. Map<Integer, Integer> map = new HashMap<Integer, Integer>();
  6. for(int num : nums1){
  7. map.put(num, map.getOrDefault(num, 0) + 1);
  8. }
  9.  
  10. List<Integer> list = new ArrayList<Integer>();
  11. for(int num : nums2){
  12. if(map.get(num) != null && map.get(num) > 0){
  13. list.add(num);
  14. map.put(num, map.get(num) - 1);
  15. }
  16. }
  17.  
  18. int k = list.size();
  19. int[] arr = new int[k];
  20. for(int num : list) arr[--k] = num;
  21.  
  22. return arr;
  23. }

242. Valid Anagram

题目描述:Given two strings s and , write a function to determine if t is an anagram of s.

202. Happy Number

290. Word Pattern

205. Isomorphic Strings

451. Sort Characters By Frequency

查找表的经典问题:

1. Two Sum

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

时间:99.77%,空间:88.15%

  1. public int[] twoSum(int[] nums, int target) {
  2. Map<Integer, Integer> map = new HashMap<Integer, Integer>();
  3. for(int i = 0; i < nums.length; i++){
  4. int de = target - nums[i];
  5. if(map.get(de) != null) return new int[]{map.get(de), i};
  6. map.put(nums[i], i);
  7. }
  8. return new int[2];
  9. }

15. 3Sum

18. 4Sum

16. 3Sum Closest

454. 4Sum II

描述:Given four lists A, B, C, D of integer values, compute how many tuples (i, j, k, l) there are such that A[i] + B[j] + C[k] + D[l] is zero.

To make problem a bit easier, all A, B, C, D have same length of N where 0 ≤ N ≤ 500. All integers are in the range of -2^28 to 2^28 - 1 and the result is guaranteed to be at most 2^31 - 1.

  1. public int fourSumCount(int[] A, int[] B, int[] C, int[] D) {
  2. Map<Integer, Integer> map = new HashMap<Integer, Integer>();
  3. for(int a : A)
  4. for(int b : B)
  5. map.put(a + b, map.getOrDefault(a + b, 0) + 1);
  6.  
  7. int res = 0;
  8. for(int c : C)
  9. for(int d : D){
  10. if(map.getOrDefault(0 - c - d, 0) > 0){
  11. res += map.get(0 - c - d);
  12. }
  13. }
  14. return res;
  15. }

49. Group Anagrams

447. Number of Boomerangs

Given n points in the plane that are all pairwise distinct, a "boomerang" is a tuple of points (i, j, k) such that the distance between i and j equals the distance between i and k (the order of the tuple matters).

Find the number of boomerangs. You may assume that nwill be at most 500 and coordinates of points are all in the range [-10000, 10000] (inclusive).

  1. public int numberOfBoomerangs(int[][] points) {
  2. if(points == null || points.length == 0) return 0;
  3. Map<Integer, Integer> maps = new HashMap<Integer, Integer>();
  4. int res = 0;
  5. for(int i = 0; i < points.length; i++){
  6. for(int j = 0; j < points.length; j++){
  7. int distance = (points[i][0] - points[j][0]) * (points[i][0] - points[j][0]) +
  8. (points[i][1] - points[j][1]) * (points[i][1] - points[j][1]);
  9. maps.put(distance, maps.getOrDefault(distance, 0) + 1);
  10. }
  11.  
  12. for(Map.Entry<Integer, Integer> map : maps.entrySet())
  13. res += map.getValue() * (map.getValue() - 1);
  14. maps.clear();
  15. }
  16.  
  17. return res;
  18. }

149. Max Points on a Line

 滑动窗口+查找表

219. Contains Duplicate II

Given an array of integers and an integer k, find out whether there are two distinct indices i and j in the array such that nums[i] = nums[j] and the absolute difference between i and j is at most k.

  1. public boolean containsNearbyDuplicate(int[] nums, int k) {
  2. if(nums == null || nums.length == 0 || k <= 0) return false;
  3. Set<Integer> set = new HashSet<Integer>();
  4.  
  5. for(int i = 0; i < nums.length; i++){
  6. if(i < k + 1) {
  7. set.add(nums[i]);
  8. if(set.size() < i+1) return true;
  9. continue;
  10. }
  11. set.remove(nums[i - k - 1]);
  12. set.add(nums[i]);
  13. if(set.size() < k+1) return true;
  14. }
  15.  
  16. return false;
  17. }

217. Contains Duplicate

220. Contains Duplicate III

Given an array of integers, find out whether there are two distinct indices i and j in the array such that the absolute difference between nums[i] and nums[j] is at most t and the absolute difference between iand j is at most k.

不是优秀的解法:

  1. public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) {
  2. if(nums == null || nums.length == 0 || t < 0 || k <= 0) return false;
  3.  
  4. TreeSet<Long> set = new TreeSet<Long>();
  5. for(int i = 0; i < nums.length; i++){
  6. if(set.ceiling((long)nums[i] - t) != null && set.floor((long)nums[i] + t) != null
  7. && set.ceiling((long)nums[i] - t) - set.floor((long)nums[i] + t) <= 2 * (long)t)
  8. return true;
  9.  
  10. set.add((long)nums[i]);
  11. if(set.size() > k) set.remove((long)nums[i - k]);
  12. }
  13.  
  14. return false;
  15. }

 链表

206. Reverse Linked List

Reverse a singly linked list.

  1. Input: 1->2->3->4->5->NULL
  2. Output: 5->4->3->2->1->NULL
  1. public ListNode reverseList(ListNode head) {
  2. ListNode pre = null;
  3. ListNode cur = head;
  4. ListNode next = null;
  5.  
  6. while(cur != null){
  7. next = cur.next;
  8. cur.next = pre;
  9. pre = cur;
  10. cur = next;
  11. }
  12.  
  13. return pre;
  14. }

92. Reverse Linked List II

链表基础操作

83. Remove Duplicates from Sorted List

86. Partition List

328. Odd Even Linked List

2. Add Two Numbers

445. Add Two Numbers II

虚拟头节点

203. Remove Linked List Elements

Remove all elements from a linked list of integers that have value val.

  1. public ListNode removeElements(ListNode head, int val) {
  2. ListNode tempNode = new ListNode(0);
  3. tempNode.next = head;
  4. ListNode cur = tempNode;
  5. while(cur.next != null){
  6. if(cur.next.val == val) cur.next = cur.next.next;
  7. else cur = cur.next;
  8. }
  9. return tempNode.next;
  10. }

82. Remove Duplicates from Sorted List II

21. Merge Two Sorted Lists

24. Swap Nodes in Pairs

Given a linked list, swap every two adjacent nodes and return its head.

You may not modify the values in the list's nodes, only nodes itself may be changed.

  1. public ListNode swapPairs(ListNode head) {
  2. ListNode top = new ListNode(0);
  3. top.next = head;
  4. ListNode node = top;
  5.  
  6. while(node.next != null && node.next.next != null){
  7. ListNode first = node.next;
  8. ListNode second = first.next;
  9.  
  10. node.next = second;
  11. first.next = second.next;
  12. second.next =first;
  13.  
  14. node = node.next.next;
  15. }
  16.  
  17. return top.next;
  18. }

25. Reverse Nodes in k-Group

链表排序

147. Insertion Sort List

148. Sort List

改变值

237. Delete Node in a Linked List

  1. class Solution {
  2. public void deleteNode(ListNode node) {
  3. node.val = node.next.val;
  4. node.next = node.next.next;
  5. }
  6. }

链表与双指针

19. Remove Nth Node From End of List

Given a linked list, remove the n-th node from the end of list and return its head.

  1. public ListNode removeNthFromEnd(ListNode head, int n) {
  2. // LeetCode对特殊情况出现的少,比如 head 为空, n的验证等
  3.  
  4. ListNode top = new ListNode(0);
  5. top.next = head;
  6.  
  7. ListNode l = top, r = top;
  8. while(n > 0){
  9. r = r.next;
  10. n--;
  11. }
  12. while(r.next != null){
  13. l = l.next;
  14. r = r.next;
  15. }
  16. l.next = l.next.next;
  17.  
  18. return top.next;
  19. }

61. Rotate List

143. Reorder List

234. Palindrome Linked List

栈和队列的使用

20. Valid Parentheses

Given a string containing just the characters '('')''{''}''[' and ']', determine if the input string is valid.

An input string is valid if:

  1. Open brackets must be closed by the same type of brackets.
  2. Open brackets must be closed in the correct order.

Note that an empty string is also considered valid.

  1. public boolean isValid(String s) {
  2. if(s == null || s.length() == 0) return true;
  3. Stack<Character> stack = new Stack<Character>();
  4. HashMap<Character, Character> map = new HashMap<Character, Character>();
  5. map.put('(', ')'); map.put('[', ']'); map.put('{', '}');
  6.  
  7. for(int i = 0; i < s.length(); i++){
  8. Character c = s.charAt(i);
  9. if(c == '(' || c == '[' || c == '{') stack.push(c);
  10. else if(stack.size() == 0) return false;
  11. else {
  12. Character c1 = map.get(stack.pop());
  13. if (c != c1) return false;
  14. }
  15. }
  16.  
  17. return stack.empty();
  18. }

150. Evaluate Reverse Polish Notation

71. Simplify Path

栈和递归

二叉树的递归:

前序遍历 144、

递归的方式

  1. public List<Integer> preorderTraversal(TreeNode root) {
  2. List<Integer> list = new ArrayList<Integer>();
  3. if(root == null) return list;
  4.  
  5. recursivePreOrder(list, root);
  6.  
  7. return list;
  8. }
  9.  
  10. private void recursivePreOrder(List<Integer> list, TreeNode root){
  11. if(root == null) return;
  12. list.add(root.val);
  13. recursivePreOrder(list, root.left);
  14. recursivePreOrder(list, root.right);
  15. }

中序遍历 94、

递归的方式

  1. public List<Integer> inorderTraversal(TreeNode root) {
  2. List<Integer> list = new ArrayList<Integer>();
  3. if(root == null) return list;
  4.  
  5. recursivePreOrder(list, root);
  6.  
  7. return list;
  8. }
  9. private void recursivePreOrder(List<Integer> list, TreeNode root){
  10. if(root == null) return;
  11. recursivePreOrder(list, root.left);
  12. list.add(root.val);
  13. recursivePreOrder(list, root.right);
  14. }

后序遍历 145

递归的方式

  1. public List<Integer> postorderTraversal(TreeNode root) {
  2. List<Integer> list = new ArrayList<Integer>();
  3. if(root == null) return list;
  4.  
  5. recursivePreOrder(list, root);
  6.  
  7. return list;
  8. }
  9. private void recursivePreOrder(List<Integer> list, TreeNode root){
  10. if(root == null) return;
  11. recursivePreOrder(list, root.left);
  12. recursivePreOrder(list, root.right);
  13. list.add(root.val);
  14. }

341. Flatten Nested List Iterator

队列

广度优先遍历

102. Binary Tree Level Order Traversal

Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).

  1. public List<List<Integer>> levelOrder(TreeNode root) {
  2. List<List<Integer>> lists = new ArrayList<List<Integer>>();
  3. if(root == null) return lists;
  4.  
  5. Queue<TreeNode> queue = new LinkedList<TreeNode>();
  6. queue.add(root);
  7. while(!queue.isEmpty()){
  8. List<Integer> list = new ArrayList<Integer>();
  9. int levelSize = queue.size();
  10. for(int i = 0; i < levelSize; i++){
  11. TreeNode node = queue.poll();
  12. if(node.left != null) queue.add(node.left);
  13. if(node.right != null) queue.add(node.right);
  14. list.add(node.val);
  15. }
  16. lists.add(list);
  17. }
  18.  
  19. return lists;
  20. }

107. Binary Tree Level Order Traversal II

103. Binary Tree Zigzag Level Order Traversal

199. Binary Tree Right Side View

BFS和图的最短路径

279. Perfect Squares

Given a positive integer n, find the least number of perfect square numbers (for example, 1, 4, 9, 16, ...) which sum to n.

  1. class Solution {
  2. // 不是我写的
  3. public int numSquares(int n) {
  4. Queue<Node> queue = new LinkedList<Node>();
  5. queue.add(new Node(n, 0));
  6. int[] visit = new int[n+1];
  7.  
  8. while(!queue.isEmpty()){
  9. Node node = queue.poll();
  10. int num = node.num;
  11. int step = node.step;
  12.  
  13. for(int i = 0; ; i++){
  14. int a = num - i * i;
  15. if(a < 0) break;
  16. if(a == 0) return step + 1;
  17. if(visit[a] == 1) continue;
  18. queue.add(new Node(num - i * i, step + 1));
  19. visit[a] = 1;
  20. }
  21. }
  22. return -1;
  23. }
  24. }
  25. class Node{
  26. int num;
  27. int step;
  28. public Node(int num, int step){
  29. this.num = num;
  30. this.step = step;
  31. }
  32. }

127. Word Ladder

126. Word Ladder II

优先队列

347. Top K Frequent Elements

23. Merge k Sorted Lists

Leetcode题目分类整理的更多相关文章

  1. LeetCode题目分类

    利用堆栈:http://oj.leetcode.com/problems/evaluate-reverse-polish-notation/http://oj.leetcode.com/problem ...

  2. LeetCode 题目总结/分类

    LeetCode 题目总结/分类 利用堆栈: http://oj.leetcode.com/problems/evaluate-reverse-polish-notation/ http://oj.l ...

  3. leetcode题目清单

    2016-09-24,开始刷leetcode上的算法题,下面整理一下leetcode题目清单.Github-leetcode 1.基本数学 Two Sum Palindrome Number Cont ...

  4. LeetCode题型分类及索引

    目录 这是一个对LeetCode题目归类的索引,分类标准参考了July大神的<编程之法>以及LeetCode的tag项.分类可能还不太合理,逐步完善,请见谅~ 题主本人也在一点一点的刷题, ...

  5. LeetCode题目解答

    LeetCode题目解答——Easy部分 Posted on 2014 年 11 月 3 日 by 四火 [Updated on 9/22/2017] 如今回头看来,里面很多做法都不是最佳的,有的从复 ...

  6. 杭电hdoj题目分类

    HDOJ 题目分类 //分类不是绝对的 //"*" 表示好题,需要多次回味 //"?"表示结论是正确的,但还停留在模块阶 段,需要理解,证明. //简单题看到就 ...

  7. poj 题目分类(1)

    poj 题目分类 按照ac的代码长度分类(主要参考最短代码和自己写的代码) 短代码:0.01K--0.50K:中短代码:0.51K--1.00K:中等代码量:1.01K--2.00K:长代码:2.01 ...

  8. POJ题目分类(按初级\中级\高级等分类,有助于大家根据个人情况学习)

    本文来自:http://www.cppblog.com/snowshine09/archive/2011/08/02/152272.spx 多版本的POJ分类 流传最广的一种分类: 初期: 一.基本算 ...

  9. ZOJ题目分类

    ZOJ题目分类初学者题: 1001 1037 1048 1049 1051 1067 1115 1151 1201 1205 1216 1240 1241 1242 1251 1292 1331 13 ...

随机推荐

  1. SpringBoot的启动配置原理

    一.启动流程 创建SpringApplication对象 public class SpringApplication { public SpringApplication(Class... prim ...

  2. 解决设置了display:none的元素,会先展示再隐藏

    问题:元素明明设置了display:none,但是在刷新页面的时候却会先显示了出来,然后才会隐藏,实现display:none 原因:由于元素渲染的时候,样式还没有应用上去,导致的 解决办法:使用内联 ...

  3. 微信小程序页面跳转区别总结

    redirectTo.navigateTo与switchTap区别 用了这么多天的页面跳转 该总结下了 redirectTo:关闭当前页,跳转到指定页:navigateTo:保留当前页,跳转到指定页: ...

  4. K2 BPM_如何将RPA的价值最大化?_全球领先的工作流引擎

     自动化技术让企业能够更有效的利用资源,减少由于人为失误而造成的风险损失.随着科技的进步,实现自动化的途径变得更加多样化. 据Forrester预测,自动化技术将在2019年成为引领数字化转型的前沿技 ...

  5. RocketMQ顺序消息

    rocketmq的顺序消息需要满足2点: 1.Producer端保证发送消息有序,且发送到同一个队列.2.consumer端保证消费同一个队列. 生产端: RocketMQ可以严格的保证消息有序.但这 ...

  6. 轻量化模型之SqueezeNet

    自 2012 年 AlexNet 以来,卷积神经网络在图像分类.目标检测.语义分割等领域获得广泛应用.随着性能要求越来越高,AlexNet 已经无法满足大家的需求,于是乎各路大牛纷纷提出性能更优越的 ...

  7. C - Calculation 2 HDU - 3501 (欧拉)

    Given a positive integer N, your task is to calculate the sum of the positive integers less than N w ...

  8. 【LOJ6671】EntropyIncreaser 与 Minecraft

    Orz lbt Description https://loj.ac/problem/6671 Solution

  9. PAT乙级1043

    题目链接 https://pintia.cn/problem-sets/994805260223102976/problems/994805280074743808 题解 这次再次体会到题意理解的正确 ...

  10. python -m pip install [package] --no-deps

    python -m pip install [package]  --no-deps 有些 packages 会依赖一些其它的 package,当我们离线安装 whl 的时候,就无法联网下载依赖包,所 ...