提交 22819ff6 编写于 作者: L liu13

20190410

上级 d0d76735
package code;
import java.util.ArrayList;
import java.util.List;
/*
* 148. Sort List
* 题意:链表排序
* 难度:Medium
* 分类:Linked List, Sort
* 思路:快慢指针把链表分成两半,在merge两个链表
* 快排方法自己不会写,记下思路
* 快排尝试直接以ListNode互相交换位置,节点间的指向会乱掉的,当递归子情况的时候会修改指针,父方法不知道子调用做了哪些操作
* https://www.cnblogs.com/morethink/p/8452914.html
* Tips:空间复杂度不是O(1)的,但是几个高票答案都是这样写的,面试给出这样的代码应该也够了
*/
public class lc148 {
......@@ -52,4 +59,40 @@ public class lc148 {
}
return head.next;
}
public ListNode sortList2(ListNode head) { //链表快排
//采用快速排序
quickSort(head, null);
return head;
}
public void quickSort(ListNode head, ListNode end) {
if (head != end) {
ListNode node = partion(head, end);
quickSort(head, node);
quickSort(node.next, end);
}
}
public ListNode partion(ListNode head, ListNode end) {
ListNode p1 = head, p2 = head.next;
//走到末尾才停
while (p2 != end) { //p1与p2间都是大于pivot的数
if (p2.val < head.val) { //lc922 类似的思想, 把小于的值放到该放的位置上
p1 = p1.next;
int temp = p1.val;
p1.val = p2.val;
p2.val = temp;
}
p2 = p2.next;
}
//与pivot交换下位置
int temp = p1.val;
p1.val = head.val;
head.val = temp;
return p1; //返回
}
}
......@@ -5,7 +5,7 @@ package code;
* 难度:Hard
* 分类:Backtracking
* 思路:回溯+判断,注意怎么判断两个斜线方向
* Tips:
* Tips:lc52
*/
import java.util.ArrayList;
import java.util.HashSet;
......
package code;
import java.util.HashSet;
/*
* 52. N-Queens II
* 题意:8皇后问题
* 难度:Hard
* 分类:Backtracking
* 思路:和 lc51 一样,输出变为种类数,反而简单了
* Tips:
*/
public class lc52 {
HashSet<String> hs = new HashSet();
int res = 0;
public int totalNQueens(int n) {
dfs(n, 0);
return res;
}
public void dfs(int n, int row){
if(row==n){
res++;
}
for (int i = 0; i < n ; i++) {
if(isValid(row, i)){
int a = row+i; // row+col 作为key
int b = row-i; // row-col 作为key
hs.add("row"+row); hs.add("col"+i); hs.add("k1"+a); hs.add("k2"+b);
dfs(n, row+1);
hs.remove("row"+row); hs.remove("col"+i); hs.remove("k1"+a); hs.remove("k2"+b); //别忘了删掉
}
}
}
public boolean isValid(int row, int col){
int a = row+col;
int b = row-col;
if(hs.contains("row"+row)||hs.contains("col"+col)||hs.contains("k1"+a)||hs.contains("k2"+b)) return false;
return true;
}
}
......@@ -9,7 +9,7 @@ import java.util.HashMap;
* 分类:Two Pointers
* 思路:由于本题只要求给出多少种Int值,所以不一定非要用3Sum的思路,有很多更简答的方法
* 3种思路
* Tips:
* Tips:lc15, lc16, lc923
*/
public class lc923 {
public int threeSumMulti(int[] A, int target) {
......@@ -53,21 +53,4 @@ public class lc923 {
return res;
}
public int threeSumMulti3(int[] A, int target) { //直接数学计算
long[] c = new long[101];
for (int a : A) c[a]++;
long res = 0;
for (int i = 0; i <= 100; i++) // 题目给了值不超过100
for (int j = i; j <= 100; j++) {
int k = target - i - j;
if (k > 100 || k < 0) continue;
if (i == j && j == k)
res += c[i] * (c[i] - 1) * (c[i] - 2) / 6;
else if (i == j && j != k)
res += c[i] * (c[i] - 1) / 2 * c[k];
else if (j < k)
res += c[i] * c[j] * c[k];
}
return (int)(res % (1e9 + 7));
}
}
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册