一、力扣
1、排序奇升偶降链表
思路:可以直接使用归并排序,也可以先拆分为两个链表,再对第二个反转,最后再合并。
public class Solution {
public ListNode sortLinkedList (ListNode head) {
// write code here
ListNode fir = new ListNode(0);
ListNode firlas = fir;
ListNode sec = new ListNode(0);
ListNode seclas = sec;
int count = 0;
while (head != null) {
if (count % 2 == 0) {
firlas.next = head;
firlas = head;
head = head.next;
firlas.next = null;
} else {
seclas.next = head;
seclas = head;
head = head.next;
seclas.next = null;
}
count++;
}
ListNode newSec = reverse(sec.next);
return merge(newSec, fir.next);
}
public ListNode reverse(ListNode head) {
ListNode pre = null;
while (head != null) {
ListNode headNext = head.next;
head.next = pre;
pre = head;
head = headNext;
}
return pre;
}
public ListNode merge(ListNode head1, ListNode head2) {
ListNode dummy = new ListNode(0);
ListNode last = dummy;
while (head1 != null && head2 != null) {
if (head1.val > head2.val) {
last.next = head2;
last = head2;
head2 = head2.next;
last.next = null;
} else {
last.next = head1;
last = head1;
head1 = head1.next;
last.next = null;
}
}
last.next = head1 == null ? head2 : head1;
return dummy.next;
}
}
2、零钱兑换 II
完全背包是从i+1,01背包是从i。
class Solution {
public int change(int amount, int[] coins) {
int n = coins.length;
int[][] dp = new int[n + 1][amount + 1];
dp[0][0] = 1;
for (int i = 0; i < n; i++) {
for (int j = 0; j <= amount; j++) {
if (j < coins[i]) {
dp[i + 1][j] = dp[i][j];
} else {
dp[i + 1][j] = dp[i][j] + dp[i + 1][j - coins[i]];
}
}
}
return dp[n][amount];
}
}
3、Pow(x, n)
class Solution {
public double myPow(double x, int n) {
double res = 1;
long ans = n;
if (ans < 0) {
ans = -ans;
x = 1 / x;
}
while (n != 0) {
if ((n & 1) == 1) {
res *= x;
}
x = x * x;
n = n / 2;
}
return res;
}
}
4、判断子序列
class Solution {
public boolean isSubsequence(String s, String t) {
int m = s.length(), n = t.length();
int[][] dp = new int[m + 1][n + 1];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (s.charAt(i) == t.charAt(j)) {
dp[i + 1][j + 1] = dp[i][j] + 1;
} else {
dp[i + 1][j + 1] = Math.max(dp[i + 1][j], dp[i][j + 1]);
}
}
}
return dp[m][n] == m;
}
}