Leetcode题目分类整理
一、数组
8) 双指针 ---- 滑动窗口
例题:
3. Longest Substring Without Repeating Characters
描述:Given a string, find the length of the longest substring without repeating characters.
题解:时间:92.67%,空间:87.02%
public int lengthOfLongestSubstring(String s) {
// check
if(s == null || s.length() == 0) return 0; // initial
int[] freq = new int[256];
Arrays.fill(freq, -1);
int l = 0, r = 0, res = 0; while(r < s.length()){
if(freq[s.charAt(r)] != -1) l = Math.max(l, freq[s.charAt(r)] + 1);
freq[s.charAt(r)] = r++;
res = Math.max(res, r - l);
} return res;
}
练习:
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.
Input: nums1 = [1,2,2,1], nums2 = [2,2]
Output: [2]
public int[] intersection(int[] nums1, int[] nums2) {
if(nums1 == null || nums1.length == 0 || nums2 == null || nums2.length == 0)
return new int[0]; Set<Integer> set1 = new HashSet<Integer>();
Set<Integer> setTemp = new HashSet<Integer>(); for(int num : nums1) set1.add(num);
for(int num : nums2) if(set1.contains(num)) setTemp.add(num); int k = setTemp.size();
int[] res = new int[k];
for(int num : setTemp) res[--k] = num; return res;
}
350. Intersection of Two Arrays II // 熟悉 Map
描述:Given two arrays, write a function to compute their intersection.
Input: nums1 = [1,2,2,1], nums2 = [2,2]
Output: [2,2]
public int[] intersect(int[] nums1, int[] nums2) {
if(nums1 == null || nums1.length == 0 || nums2 == null || nums2.length == 0)
return new int[0]; Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for(int num : nums1){
map.put(num, map.getOrDefault(num, 0) + 1);
} List<Integer> list = new ArrayList<Integer>();
for(int num : nums2){
if(map.get(num) != null && map.get(num) > 0){
list.add(num);
map.put(num, map.get(num) - 1);
}
} int k = list.size();
int[] arr = new int[k];
for(int num : list) arr[--k] = num; return arr;
}
242. Valid Anagram
题目描述:Given two strings s and t , 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%
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for(int i = 0; i < nums.length; i++){
int de = target - nums[i];
if(map.get(de) != null) return new int[]{map.get(de), i};
map.put(nums[i], i);
}
return new int[2];
}
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.
public int fourSumCount(int[] A, int[] B, int[] C, int[] D) {
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for(int a : A)
for(int b : B)
map.put(a + b, map.getOrDefault(a + b, 0) + 1); int res = 0;
for(int c : C)
for(int d : D){
if(map.getOrDefault(0 - c - d, 0) > 0){
res += map.get(0 - c - d);
}
}
return res;
}
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).
public int numberOfBoomerangs(int[][] points) {
if(points == null || points.length == 0) return 0;
Map<Integer, Integer> maps = new HashMap<Integer, Integer>();
int res = 0;
for(int i = 0; i < points.length; i++){
for(int j = 0; j < points.length; j++){
int distance = (points[i][0] - points[j][0]) * (points[i][0] - points[j][0]) +
(points[i][1] - points[j][1]) * (points[i][1] - points[j][1]);
maps.put(distance, maps.getOrDefault(distance, 0) + 1);
} for(Map.Entry<Integer, Integer> map : maps.entrySet())
res += map.getValue() * (map.getValue() - 1);
maps.clear();
} return res;
}
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.
public boolean containsNearbyDuplicate(int[] nums, int k) {
if(nums == null || nums.length == 0 || k <= 0) return false;
Set<Integer> set = new HashSet<Integer>(); for(int i = 0; i < nums.length; i++){
if(i < k + 1) {
set.add(nums[i]);
if(set.size() < i+1) return true;
continue;
}
set.remove(nums[i - k - 1]);
set.add(nums[i]);
if(set.size() < k+1) return true;
} return false;
}
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.
不是优秀的解法:
public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) {
if(nums == null || nums.length == 0 || t < 0 || k <= 0) return false; TreeSet<Long> set = new TreeSet<Long>();
for(int i = 0; i < nums.length; i++){
if(set.ceiling((long)nums[i] - t) != null && set.floor((long)nums[i] + t) != null
&& set.ceiling((long)nums[i] - t) - set.floor((long)nums[i] + t) <= 2 * (long)t)
return true; set.add((long)nums[i]);
if(set.size() > k) set.remove((long)nums[i - k]);
} return false;
}
链表
206. Reverse Linked List
Reverse a singly linked list.
Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL
public ListNode reverseList(ListNode head) {
ListNode pre = null;
ListNode cur = head;
ListNode next = null; while(cur != null){
next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
} return pre;
}
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.
public ListNode removeElements(ListNode head, int val) {
ListNode tempNode = new ListNode(0);
tempNode.next = head;
ListNode cur = tempNode;
while(cur.next != null){
if(cur.next.val == val) cur.next = cur.next.next;
else cur = cur.next;
}
return tempNode.next;
}
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.
public ListNode swapPairs(ListNode head) {
ListNode top = new ListNode(0);
top.next = head;
ListNode node = top; while(node.next != null && node.next.next != null){
ListNode first = node.next;
ListNode second = first.next; node.next = second;
first.next = second.next;
second.next =first; node = node.next.next;
} return top.next;
}
25. Reverse Nodes in k-Group
链表排序
147. Insertion Sort List
148. Sort List
改变值
237. Delete Node in a Linked List
class Solution {
public void deleteNode(ListNode node) {
node.val = node.next.val;
node.next = node.next.next;
}
}
链表与双指针
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.
public ListNode removeNthFromEnd(ListNode head, int n) {
// LeetCode对特殊情况出现的少,比如 head 为空, n的验证等 ListNode top = new ListNode(0);
top.next = head; ListNode l = top, r = top;
while(n > 0){
r = r.next;
n--;
}
while(r.next != null){
l = l.next;
r = r.next;
}
l.next = l.next.next; return top.next;
}
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:
- Open brackets must be closed by the same type of brackets.
- Open brackets must be closed in the correct order.
Note that an empty string is also considered valid.
public boolean isValid(String s) {
if(s == null || s.length() == 0) return true;
Stack<Character> stack = new Stack<Character>();
HashMap<Character, Character> map = new HashMap<Character, Character>();
map.put('(', ')'); map.put('[', ']'); map.put('{', '}'); for(int i = 0; i < s.length(); i++){
Character c = s.charAt(i);
if(c == '(' || c == '[' || c == '{') stack.push(c);
else if(stack.size() == 0) return false;
else {
Character c1 = map.get(stack.pop());
if (c != c1) return false;
}
} return stack.empty();
}
150. Evaluate Reverse Polish Notation
71. Simplify Path
栈和递归
二叉树的递归:
前序遍历 144、
递归的方式
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> list = new ArrayList<Integer>();
if(root == null) return list; recursivePreOrder(list, root); return list;
} private void recursivePreOrder(List<Integer> list, TreeNode root){
if(root == null) return;
list.add(root.val);
recursivePreOrder(list, root.left);
recursivePreOrder(list, root.right);
}
中序遍历 94、
递归的方式
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> list = new ArrayList<Integer>();
if(root == null) return list; recursivePreOrder(list, root); return list;
}
private void recursivePreOrder(List<Integer> list, TreeNode root){
if(root == null) return;
recursivePreOrder(list, root.left);
list.add(root.val);
recursivePreOrder(list, root.right);
}
后序遍历 145
递归的方式
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> list = new ArrayList<Integer>();
if(root == null) return list; recursivePreOrder(list, root); return list;
}
private void recursivePreOrder(List<Integer> list, TreeNode root){
if(root == null) return;
recursivePreOrder(list, root.left);
recursivePreOrder(list, root.right);
list.add(root.val);
}
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).
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> lists = new ArrayList<List<Integer>>();
if(root == null) return lists; Queue<TreeNode> queue = new LinkedList<TreeNode>();
queue.add(root);
while(!queue.isEmpty()){
List<Integer> list = new ArrayList<Integer>();
int levelSize = queue.size();
for(int i = 0; i < levelSize; i++){
TreeNode node = queue.poll();
if(node.left != null) queue.add(node.left);
if(node.right != null) queue.add(node.right);
list.add(node.val);
}
lists.add(list);
} return lists;
}
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.
class Solution {
// 不是我写的
public int numSquares(int n) {
Queue<Node> queue = new LinkedList<Node>();
queue.add(new Node(n, 0));
int[] visit = new int[n+1]; while(!queue.isEmpty()){
Node node = queue.poll();
int num = node.num;
int step = node.step; for(int i = 0; ; i++){
int a = num - i * i;
if(a < 0) break;
if(a == 0) return step + 1;
if(visit[a] == 1) continue;
queue.add(new Node(num - i * i, step + 1));
visit[a] = 1;
}
}
return -1;
}
}
class Node{
int num;
int step;
public Node(int num, int step){
this.num = num;
this.step = step;
}
}
127. Word Ladder
126. Word Ladder II
优先队列
347. Top K Frequent Elements
23. Merge k Sorted Lists
Leetcode题目分类整理的更多相关文章
- LeetCode题目分类
利用堆栈:http://oj.leetcode.com/problems/evaluate-reverse-polish-notation/http://oj.leetcode.com/problem ...
- LeetCode 题目总结/分类
LeetCode 题目总结/分类 利用堆栈: http://oj.leetcode.com/problems/evaluate-reverse-polish-notation/ http://oj.l ...
- leetcode题目清单
2016-09-24,开始刷leetcode上的算法题,下面整理一下leetcode题目清单.Github-leetcode 1.基本数学 Two Sum Palindrome Number Cont ...
- LeetCode题型分类及索引
目录 这是一个对LeetCode题目归类的索引,分类标准参考了July大神的<编程之法>以及LeetCode的tag项.分类可能还不太合理,逐步完善,请见谅~ 题主本人也在一点一点的刷题, ...
- LeetCode题目解答
LeetCode题目解答——Easy部分 Posted on 2014 年 11 月 3 日 by 四火 [Updated on 9/22/2017] 如今回头看来,里面很多做法都不是最佳的,有的从复 ...
- 杭电hdoj题目分类
HDOJ 题目分类 //分类不是绝对的 //"*" 表示好题,需要多次回味 //"?"表示结论是正确的,但还停留在模块阶 段,需要理解,证明. //简单题看到就 ...
- poj 题目分类(1)
poj 题目分类 按照ac的代码长度分类(主要参考最短代码和自己写的代码) 短代码:0.01K--0.50K:中短代码:0.51K--1.00K:中等代码量:1.01K--2.00K:长代码:2.01 ...
- POJ题目分类(按初级\中级\高级等分类,有助于大家根据个人情况学习)
本文来自:http://www.cppblog.com/snowshine09/archive/2011/08/02/152272.spx 多版本的POJ分类 流传最广的一种分类: 初期: 一.基本算 ...
- ZOJ题目分类
ZOJ题目分类初学者题: 1001 1037 1048 1049 1051 1067 1115 1151 1201 1205 1216 1240 1241 1242 1251 1292 1331 13 ...
随机推荐
- 小知识:修改IDEA的模板
小知识:修改IDEA的模板 有时候我们会发现,IDEA默认创建的模板并不是我们常用的.与其每次都在创建后进行修改,不如直接对模板进行修改. 给不知道怎么修改的同学指一下路: File->sett ...
- asp.net mvc 导出Excel
[HttpGet] public void ExportNissan(string CheckListNo) { JObject queryParam; if (CheckListNo == null ...
- Scala语言基础
1. Scala语言的特点 a. 多范式编程语言,面向对象(抽象.封装)和函数式(过程.结果)编程 b. 代码简洁 ==>可读性较差 c. 代码会被变异成Java字节码,运行在JVM上 2. S ...
- Oracle和MySql的分页查询区别和PL/SQL的基本概念
Oracle和MySql的分页查询区别: Oracle的分析查询,之前Oracle的分页是使用伪列 ROWNUM 结合子查询实现,mysql的分页更简单,直接使用 LIMIT 关键字就可以实现 ...
- Python入门之第三方模块安装
Python入门之第三方模块安装 平台:Win10 x64 + Anaconda3-5.3.0 (+Python3.7.0) Issue说明:pip install line_profiler-2.1 ...
- PAT Basic 1059 C语言竞赛 (20 分)
C 语言竞赛是浙江大学计算机学院主持的一个欢乐的竞赛.既然竞赛主旨是为了好玩,颁奖规则也就制定得很滑稽: 0.冠军将赢得一份“神秘大奖”(比如很巨大的一本学生研究论文集……). 1.排名为素数的学生将 ...
- 关于Linux连接工具mobaxterm显示中文乱码问题
本人用的是MobaXterm Personal 9.1版本.近期发现连接上服务器,查看日志时,发现中文乱码,无法正常显示.甚是苦恼.百度搜索该工具显示乱码问题,无一人解决.提倡更换连接工具.无意间发现 ...
- PHP判断是否有Get参数的方法
PHP如何判断是否有Get参数,方法很简单,一个函数就可以搞定,需要的朋友可以参考下 if(is_array($_GET)&&count($_GET)>0)//判断是否有Get参 ...
- 数据库底层索引为什么用B树
注意B-树就是B树,-只是一个符号. 简介 B/B+树是为了磁盘或其它存储设备而设计的一种平衡多路查找树(相对于二叉,B树每个内节点有多个分支),与红黑树相比,在相同的的节点的情况下,一颗B/B+树的 ...
- Excel 中大量图片如何快速导出? 转载自:http://www.zhihu.com/question/20800948
我的办法如下,应该也不慢. 如果是针对以.xlsx为后缀的表格(Excel2007以上的版本),这样做:显示后缀的情况下,直接重命名,把后缀.xlsx改成.rar或者.zip,然后解压出里面的图片文件 ...