43. 字符串相乘
class Solution { public String multiply(String num1, String num2) { if (num1 == null || num1.length() == 0 || num2 == null || num2.length() == 0) return ""; if (num1.equals("0") || num2.equals("0")) return "0"; int len1 = num1.length(); int len2 = num2.length(); int[] ansArr = new int[len1 + len2]; for (int i = len1 - 1; i >= 0; i--) { int x = num1.charAt(i) - '0'; for (int j = len2 - 1; j >= 0; j--) { int y = num2.charAt(j) - '0'; ansArr[i + j + 1] += x * y; } } for (int i = len1 + len2 - 1; i > 0; i--) { ansArr[i - 1] += ansArr[i] / 10; ansArr[i] %= 10; } StringBuilder ans = new StringBuilder(); int idx = ansArr[0] == 0 ? 1 : 0; while (idx < len1 + len2) { ans.append(ansArr[idx]); idx++; } return ans.toString(); }}
912. 排序数组
class Solution { public int[] sortArray(int[] nums) { quickSort(nums, 0, nums.length - 1); return nums; } void quickSort(int[] nums, int L, int R) { if (L >= R) return; int left = L, right = R; int pivot = nums[left]; while (left < right) { while (left < right && nums[right] >= pivot) right--; if (left < right) nums[left] = nums[right]; while (left < right && nums[left] <= pivot) left++; if (left < right) nums[right] = nums[left]; if (left >= right) nums[left] = pivot; } quickSort(nums, L, right - 1); quickSort(nums, right + 1, R); } void bubbleSort(int[] nums) { for (int i = 0; i < nums.length - 1; i++) { for (int j = 0; j < nums.length - 1; j++) { if (nums[j] > nums[j + 1]) { swap(nums, j, j + 1); } } } } void swap(int[] nums, int i, int j) { if (nums[i] == nums[j]) return; nums[i] = nums[i] ^ nums[j]; nums[j] = nums[i] ^ nums[j]; nums[i] = nums[i] ^ nums[j]; }}
396. 旋转函数
class Solution { public int maxRotateFunction(int[] nums) { if (nums == null || nums.length == 0) return 0; int f = 0, n = nums.length, numSum = Arrays.stream(nums).sum(); for (int i = 0; i < n; i++) { f += i * nums[i]; } int res = f; for (int i = n - 1; i > 0; i--) { f += numSum - n * nums[i]; res = Math.max(res, f); } return res; }}
206. 反转链表
public class Solution { public ListNode reverseList(ListNode head) { if (head == null || head.next == null) return head; ListNode last = reverseList(head.next); head.next.next = head; head.next = null; return last; } public ListNode reverseList2(ListNode head) { ListNode prev = null; ListNode curr = head; while (curr != null) { ListNode next = curr.next; curr.next = prev; prev = curr; curr = next; } return prev; }}