1. 两数之和
class Solution {
public int[] twoSum(int[] nums, int target) {
for(int i=0;i<nums.length;i++){
for(int j=0;j<nums.length;j++){
if(i==j)
continue;
if(nums[i]+nums[j]==target){
return new int[]{i,j};
}
}
}
return null;
}
}
2. 两数相加
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
private ListNode result;
private boolean flag = false;
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
int r = l1.val + l2.val;
if (flag) {
flag = false;
r += 1;
}
if (result == null) {
if (r > 9) {
flag = true;
result = new ListNode(r % 10);
} else {
result = new ListNode(r);
}
} else {
if (r > 9) {
flag = true;
getNullNode(result).next = new ListNode(r % 10);
} else {
getNullNode(result).next = new ListNode(r);
}
}
if (l1.next != null && l2.next != null) {
return addTwoNumbers(l1.next, l2.next);
} else if (l1.next != null) {
return addTwoNumbers(l1.next, new ListNode(0));
} else if (l2.next != null) {
return addTwoNumbers(new ListNode(0), l2.next);
}
if (flag) {
getNullNode(result).next = new ListNode(1);
}
return result;
}
private ListNode getNullNode(ListNode r) {
if (r.next != null) {
return getNullNode(r.next);
}
return r;
}
}
771. 宝石与石头
class Solution {
public int numJewelsInStones(String J, String S) {
int total = 0;
char[] diamond = J.toCharArray();
char[] stone = S.toCharArray();
for (char c : stone) {
for (char c1 : diamond) {
if (c == c1)
total++;
}
}
return total;
}
}
807. 保持城市天际线
class Solution {
public int maxIncreaseKeepingSkyline(int[][] grid) {
int total = 0;
int[] horizontalMax = getHorizontalMax(grid);
int[] verticalMax = getVerticalMax(grid);
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[0].length; j++) {
int min = horizontalMax[i] < verticalMax[j] ? horizontalMax[i] : verticalMax[j];
total += min - grid[i][j];
}
}
return total;
}
private int[] getHorizontalMax(int[][] grid) {
int[] maxArray = new int[grid.length];
for (int i = 0; i < grid.length; i++) {
maxArray[i] = Arrays.stream(grid[i]).max().getAsInt();
}
return maxArray;
}
private int[] getVerticalMax(int[][] grid) {
int[] maxArray = new int[grid.length];
for (int i = 0; i < grid[0].length; i++) {
int[] tempArry = new int[grid[0].length];
for (int j = 0; j < grid.length; j++) {
tempArry[j] = grid[j][i];
}
maxArray[i] = Arrays.stream(tempArry).max().getAsInt();
}
return maxArray;
}
}
Arrays.sort()
排序会改变数组内部的顺序Arrays.stream
则不会
929. 独特的电子邮件地址
class Solution {
public int numUniqueEmails(String[] emails) {
Set<String> emailSet = new HashSet<>();
for (String email : emails) {
String[] s1 = email.split("@");
if (s1.length != 2) {
continue;
}
String[] s2 = s1[0].split("\\+");
String s = s2[0].replace(".", "");
emailSet.add(s + "@" + s1[1]);
}
return emailSet.size();
}
}
182. 查找重复的电子邮箱
select Email from Person group by Email having count(Email) > 1
59. 螺旋矩阵 II
class Solution {
public int[][] generateMatrix(int n) {
if (n == 1) {
return new int[][] {{1}};
}
int[][] result = new int[n][n];
return getNumb(result, 1, n, 0, 0);
}
private int[][] getNumb(int[][] result, int flag, int n, int start, int level) {
if ((n * n) == start) {
return result;
} else {
if (flag == 1) {
for (int i = level; i < n - level; i++) {
result[level][i] = ++start;
}
return getNumb(result, 2, n, start, level);
} else if (flag == 2) {
for (int i = level + 1; i < n - level; i++) {
result[i][n - level - 1] = ++start;
}
return getNumb(result, 3, n, start, level);
} else if (flag == 3) {
for (int i = n - level - 2; i >= level; i--) {
result[n - level - 1][i] = ++start;
}
return getNumb(result, 4, n, start, level);
} else {
for (int i = n - level - 2; i >= level + 1; i--) {
result[i][level] = ++start;
}
return getNumb(result, 1, n, start, level += 1);
}
}
}
}
905. 按奇偶排序数组
class Solution {
public int[] sortArrayByParity(int[] A) {
int[] result = new int[A.length];
int start = 0;
int end = A.length - 1;
for (int i : A) {
if (i % 2 == 0) {
result[start++] = i;
} else {
result[end--] = i;
}
}
return result;
}
}
78. 子集
class Solution {
public List<List<Integer>> subsets(int[] nums) {
List<List<Integer>> lists = new ArrayList<>();
lists.add(new ArrayList<>());
for (int num : nums) {
lists = getNewList(lists, num);
}
return lists;
}
private List<List<Integer>> getNewList(List<List<Integer>> lists, int num) {
List<List<Integer>> list = deepCopy(lists);
List<List<Integer>> newList = lists.stream().peek(x -> x.add(num)).collect(Collectors.toList());
newList.addAll(list);
return newList;
}
private List<List<Integer>> deepCopy(List<List<Integer>> lists) {
List<List<Integer>> newList = new ArrayList<>();
for (List<Integer> list : lists) {
List<Integer> temp = new ArrayList<>(list);
newList.add(temp);
}
return newList;
}
}
338. 比特位计数
class Solution {
public int[] countBits(int num) {
int[] result = new int[num + 1];
for (int i = 0; i <= num; i++) {
result[i] = getCount(Integer.toBinaryString(i));
}
return result;
}
private int getCount(String str) {
str = str.replace("0", "");
return str.length();
}
}
832. 翻转图像
class Solution {
public int[][] flipAndInvertImage(int[][] A) {
int[][] result = new int[A.length][];
for (int i = 0; i < A.length; i++) {
String str = new StringBuilder(Arrays.toString(A[i])).reverse().toString();
str = str.replace("[", "");
str = str.replace("]", "");
str = str.replace("0", "2");
str = str.replace("1", "0");
str = str.replace("2", "1");
str = str.replace(" ", "");
String[] strs = str.split(",");
result[i] = getNumbs(strs);
}
return result;
}
private int[] getNumbs(String[] strs) {
int[] numbs = new int[strs.length];
for (int i = 0; i < strs.length; i++) {
numbs[i] = Integer.parseInt(strs[i]);
}
return numbs;
}
}
950. 按递增顺序显示卡牌
class Solution {
public int[] deckRevealedIncreasing(int[] deck) {
if (deck.length == 1) {
return new int[] {1};
}
Arrays.sort(deck);
Deque<Integer> r = new ArrayDeque<>();
r.addFirst(deck[deck.length - 1]);
r.addFirst(deck[deck.length - 2]);
for (int i = deck.length - 3; i >= 0; i--) {
r.addFirst(r.pollLast());
r.addFirst(deck[i]);
}
int[] result = new int[deck.length];
int i = 0;
for (Integer integer : r) {
result[i++] = integer;
}
return result;
}
}
627. 交换工资
UPDATE salary set sex = (CASE sex WHEN 'm' THEN 'f' ELSE 'm' END);
804. 唯一摩尔斯密码词
class Solution {
private final String[] password = {".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-",
".-..", "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--.."};
public int uniqueMorseRepresentations(String[] words) {
Set<String> set = new HashSet<>();
for (String word : words) {
StringBuilder str = new StringBuilder();
char[] chars = word.toCharArray();
for (char c : chars) {
str.append(password[c - 97]);
}
set.add(str.toString());
}
return set.size();
}
}
461. 汉明距离
class Solution {
public int hammingDistance(int x, int y) {
int z = x ^ y;
String s = Integer.toBinaryString(z);
return s.replace("0", "").length();
}
}
657. 机器人能否返回原点
class Solution {
public boolean judgeCircle(String moves) {
int l = 0, r = 0, u = 0, d = 0;
for (char c : moves.toCharArray()) {
if (c == 'U') {
u++;
} else if (c == 'D') {
d++;
} else if (c == 'L') {
l++;
} else {
r++;
}
}
return (r == l && u == d);
}
}
922. 按奇偶排序数组 II
class Solution {
public int[] sortArrayByParityII(int[] A) {
int[] result = new int[A.length];
int[] temp = new int[A.length];
int start = 0;
int end = A.length - 1;
for (int i = 0; i < A.length; i++) {
if (A[i] % 2 == 0) {
temp[start++] = A[i];
} else {
temp[end--] = A[i];
}
}
int half = A.length / 2;
for (int i = 0, j = 0; i < half; i++) {
result[j] = temp[i];
result[j + 1] = temp[half + i];
j += 2;
}
return result;
}
}
921. 使括号有效的最少添加
class Solution {
public int minAddToMakeValid(String S) {
if (S.contains("()")) {
S = S.replace("()", "");
return minAddToMakeValid(S);
} else {
return S.length();
}
}
}
852. 山脉数组的峰顶索引
class Solution {
public int peakIndexInMountainArray(int[] A) {
int max = Arrays.stream(A).max().getAsInt();
for (int i = 0; i < A.length; i++) {
if (A[i] == max) {
return i;
}
}
return -1;
}
}
814. 二叉树剪枝
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode pruneTree(TreeNode root) {
setNode(root);
return root;
}
private TreeNode setNode(TreeNode root) {
if (root == null) { return null; }
if (root.left == null && root.right == null && root.val == 0) {
return null;
}
root.left = setNode(root.left);
root.right = setNode(root.right);
return (root.left == null && root.right == null && root.val == 0) ? null : root;
}
}
104. 二叉树的最大深度
class Solution {
public int maxDepth(TreeNode root) {
return root == null ? 0 : Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;
}
}
942. 增减字符串匹配
class Solution {
public int[] diStringMatch(String S) {
int start = 0, end = S.length();
int[] result = new int[end + 1];
char[] chars = S.toCharArray();
for (int i = 0; i < chars.length; i++) {
if (chars[i] == 'I') {
result[i] = start++;
} else {
result[i] = end--;
}
if (i == chars.length - 1) {
if (chars[chars.length - 1] == 'I') {
result[chars.length] = start++;
} else {
result[chars.length] = end++;
}
}
}
return result;
}
}
476. 数字的补数
class Solution {
public int findComplement(int num) {
return num ^ ((1 << Integer.toBinaryString(num).length()) - 1);
}
}
226. 翻转二叉树
class Solution {
public TreeNode invertTree(TreeNode root) {
if (root == null) { return null; }
if (root.left != null || root.right != null) {
TreeNode temp = root.right;
root.right = root.left;
root.left = temp;
}
root.left = invertTree(root.left);
root.right = invertTree(root.right);
return root;
}
}
617. 合并二叉树
class Solution {
public TreeNode mergeTrees(TreeNode t1, TreeNode t2) {
if (t1 == null && t2 == null) { return null; }
if (t1 == null) {
return t2;
}
if (t2 == null) {
return t1;
}
t1.val += t2.val;
t1.left = mergeTrees(t1.left, t2.left);
t1.right = mergeTrees(t1.right, t2.right);
return t1;
}
}
728. 自除数
class Solution {
public List<Integer> selfDividingNumbers(int left, int right) {
if (left > right) { return null; }
List<Integer> result = new ArrayList<>();
for (; left <= right; left++) {
String leftStr = left + "";
if (leftStr.contains("0")) { continue; }
boolean flag = true;
for (char c : leftStr.toCharArray()) {
if (left % (c - 48) != 0) {
flag = false;
break;
}
}
if (flag) {
result.add(left);
}
}
return result;
}
}
500. 键盘行
class Solution {
private String s1 = "qwertyuiop";
private String s2 = "asdfghjkl";
private String s3 = "zxcvbnm";
public String[] findWords(String[] words) {
List<String> strs = new ArrayList<>();
for (String word : words) {
if (isAdd(s1, word) || isAdd(s2, word) || isAdd(s3, word)) {
strs.add(word);
}
}
return strs.toArray(new String[strs.size()]);
}
private boolean isAdd(String key, String word) {
for (char c : word.toLowerCase().toCharArray()) {
if (!key.contains(c + "")) {
return false;
}
}
return true;
}
}
590. N叉树的后序遍历
/*
// Definition for a Node.
class Node {
public int val;
public List children;
public Node() {}
public Node(int _val,List _children) {
val = _val;
children = _children;
}
};
*/
class Solution {
private List<Integer> result = new ArrayList<>();
public List<Integer> postorder(Node root) {
if (root == null) return result;
if (root.children != null) {
for (Node child : root.children) {
postorder(child);
}
}
result.add(root.val);
return result;
}
}
944. 删列造序
class Solution {
public int minDeletionSize(String[] A) {
int n=0;
for (int i=0;i<A[0].length();i++){
for (int j=0;j<A.length-1;j++){
if(A[j].charAt(i)>A[j+1].charAt(i)){
n++;
break;
}
}
}
return n;
}
}
890. 查找和替换模式
class Solution {
public List<String> findAndReplacePattern(String[] words, String pattern) {
List<String> result = new ArrayList<>();
String newPattern = getNewStr(pattern.toLowerCase(), 'A');
for (String word : words) {
if (getNewStr(word.toLowerCase(), 'A').equals(newPattern)) {
result.add(word);
}
}
return result;
}
private String getNewStr(String str, char start) {
for (char c : str.toCharArray()) {
if (c >= 'a' && c <= 'z') {
str = str.replace(c, start);
return getNewStr(str, (char)(start + 1));
}
}
return str;
}
}
94. 二叉树的中序遍历
class Solution {
private List<Integer> result = new ArrayList<>();
public List<Integer> inorderTraversal(TreeNode root) {
if (root != null) {
inorderTraversal(root.left);
result.add(root.val);
inorderTraversal(root.right);
}
return result;
}
}
145. 二叉树的后序遍历
class Solution {
private List<Integer> result = new ArrayList<>();
public List<Integer> postorderTraversal(TreeNode root) {
if (root != null) {
postorderTraversal(root.left);
postorderTraversal(root.right);
result.add(root.val);
}
return result;
}
}
559. N叉树的最大深度
class Solution {
private int max = 0;
public int maxDepth(Node root) {
getMax(root, 0);
return max;
}
private int getMax(Node root, int deep) {
if (root == null) return deep;
deep++;
if (root.children != null) {
for (Node child : root.children) {
getMax(child, deep);
}
}
max = deep > max ? deep : max;
return deep;
}
}
171. Excel表列序号
class Solution {
public int titleToNumber(String s) {
int sum = 0;
int length = s.length();
for (char c : s.toCharArray()) {
sum += getNumb(c - 64, --length);
}
return sum;
}
private int getNumb(int n1, int n) {
return (int)(Math.pow(26, n) * n1);
}
}
258. 各位相加
class Solution {
public int addDigits(int num) {
if ((num + "").length() == 1) {
return num;
} else {
int total = 0;
for (char c : (num + "").toCharArray()) {
total += c - 48;
}
return addDigits(total);
}
}
}
763. 划分字母区间
class Solution {
private List<Integer> result = new ArrayList<>();
public List<Integer> partitionLabels(String S) {
if (S == null) return result;
if (S.length() != 0) {
char[] chars = S.toCharArray();
int end = S.lastIndexOf(chars[0]) + 1;
if (S.length() == end) {
result.add(end);
return result;
}
for (int i = 0; i < end; i++) {
int e = S.lastIndexOf(chars[i]) + 1;
if (e > end) end = e;
}
result.add(end);
partitionLabels(S.substring(end));
}
return result;
}
}
137. 只出现一次的数字 II
class Solution {
public int singleNumber(int[] nums) {
for (int i = 0; i < nums.length; i++) {
int flag = 0;
for (int i1 = 0; i1 < nums.length; i1++) {
if (nums[i] == nums[i1]) { flag++; }
}
if (flag == 1) { return nums[i]; }
}
return 0;
}
}
513. 找树左下角的值
class Solution {
private int maxDeep = 0, deep = 1, result;
public int findBottomLeftValue(TreeNode root) {
if (maxDeep == 0) {
maxDeep = getDeep(root);
}
if (deep == maxDeep) {
result = root.val;
deep = -99;
}
if (root.left != null) {
deep++;
findBottomLeftValue(root.left);
deep--;
}
if (root.right != null) {
deep++;
findBottomLeftValue(root.right);
deep--;
}
return result;
}
private int getDeep(TreeNode root) {
return root == null ? 0 : Math.max(getDeep(root.left), getDeep(root.right)) + 1;
}
}
557. 反转字符串中的单词 III
class Solution {
public String reverseWords(String s) {
return Arrays.stream(s.split(" ")).map(x -> {
return new StringBuilder(x).reverse();
}).collect(Collectors.joining(" "));
}
}
908. 最小差值 I
class Solution {
public int smallestRangeI(int[] A, int K) {
if (A.length == 1) { return 0; }
Arrays.sort(A);
int max = A[A.length - 1] - 2 * K;
return max > A[0] ? max - A[0] : 0;
}
}
260. 只出现一次的数字 III
class Solution {
public int[] singleNumber(int[] nums) {
if (nums.length < 2) { return nums; }
Arrays.sort(nums);
List<Integer> list = new ArrayList<>();
if (nums[0] != nums[1]) {
list.add(nums[0]);
}
if (nums[nums.length - 1] != nums[nums.length - 2]) {
list.add(nums[nums.length - 1]);
}
for (int i = 1; i < nums.length - 1; i++) {
if (nums[i] != nums[i - 1] && nums[i] != nums[i + 1]) {
list.add(nums[i]);
}
}
int[] result = new int[list.size()];
for (int i = 0; i < list.size(); i++) {
result[i] = list.get(i);
}
return result;
}
}
561. 数组拆分 I
class Solution {
public int arrayPairSum(int[] nums) {
Arrays.sort(nums);
int total = 0;
for (int i = 1; i < nums.length; i += 2) {
total += Math.min(nums[i], nums[i - 1]);
}
return total;
}
}
230. 二叉搜索树中第K小的元素
class Solution {
public int kthSmallest(TreeNode root, int k) {
List<Integer> result = new ArrayList<>();
getResult(root, result);
return result.stream().distinct().sorted().collect(Collectors.toList()).get(k - 1);
}
private void getResult(TreeNode root, List<Integer> result) {
if (root == null) { return; }
result.add(root.val);
getResult(root.left, result);
getResult(root.right, result);
}
}
821. 字符的最短距离
class Solution {
public int[] shortestToChar(String S, char C) {
char[] chars = S.toCharArray();
int[] result = new int[chars.length];
int preIndex = -1;
for (int i = 0; i < chars.length; i++) {
if (chars[i] == C) {
preIndex = i;
result[i] = 0;
} else {
if (preIndex == -1) {
result[i] = S.indexOf(C) - i;
} else {
result[i] = S.indexOf(C, i) == -1 ? i - preIndex : Math.min(i - preIndex, S.indexOf(C, i) - i);
}
}
}
return result;
}
}
700. 二叉搜索树中的搜索
class Solution {
private TreeNode r;
public TreeNode searchBST(TreeNode root, int val) {
if (root == null) { return null; }
if (val == root.val) {
r = root;
}
searchBST(root.left, val);
searchBST(root.right, val);
return r;
}
}
89. 格雷编码
class Solution {
public List<Integer> grayCode(int n) {
List<Integer> list = new ArrayList<>();
list.add(0);
if (n == 0) { return list; }
list.add(1);
if (n == 1) { return list; }
getCode(list, 1, n);
return list;
}
public List<Integer> getCode(List<Integer> r, int start, int end) {
if (start == end) {
return r;
} else {
int size = r.size();
for (int i = size - 1; i >= 0; i--) {
r.add((1 << start) ^ r.get(i));
}
return getCode(r, start + 1, end);
}
}
}
class Solution {
public List<Integer> grayCode(int n) {
List<Integer> list = new ArrayList<>();
for (int i = 0; i < Math.pow(2, n); i++) {
list.add(i ^ (i >> 1));
}
return list;
}
}
811. 子域名访问计数
class Solution {
public List<String> subdomainVisits(String[] cpdomains) {
Map<String, Integer> map = new HashMap<>();
for (String cpdomain : cpdomains) {
String[] s = cpdomain.split(" ");
int num = Integer.parseInt(s[0]);
addDomain(map, s[1], num);
}
List<String> result = map.entrySet().stream().map(x -> x.getValue() + " " + x.getKey()).collect(
Collectors.toList());
return result;
}
private void addDomain(Map<String, Integer> map, String s, int num) {
if (map.containsKey(s)) {
map.put(s, map.get(s) + num);
} else {
map.put(s, num);
}
if (s.contains(".")) {
addDomain(map, s.substring(s.indexOf(".") + 1), num);
}
}
}
181. 超过经理收入的员工
select e1.Name as Employee from Employee as e1 ,Employee as e2 where e1.ManagerId = e2.Id AND e1.Salary > e2.Salary
693. 交替位二进制数
class Solution {
public boolean hasAlternatingBits(int n) {
char[] chars = Integer.toBinaryString(n).toCharArray();
for (int i = 0; i < chars.length - 1; i++) {
if (chars[i] == chars[i + 1]) { return false; }
}
return true;
}
}
108. 将有序数组转换为二叉搜索树
class Solution {
public TreeNode sortedArrayToBST(int[] nums) {
// 左右等分建立左右子树,中间节点作为子树根节点,递归该过程
if (nums == null || nums.length == 0) {
return null;
}
return buildTree(nums, 0, nums.length - 1);
}
private TreeNode buildTree(int[] nums, int l, int r) {
if (l > r) {
return null;
}
if (l == r) {
return new TreeNode(nums[l]);
}
int mid = (l + r) / 2;
TreeNode root = new TreeNode(nums[mid]);
root.left = buildTree(nums, l, mid - 1);
root.right = buildTree(nums, mid + 1, r);
return root;
}
}
109. 有序链表转换二叉搜索树
class Solution {
public TreeNode sortedListToBST(ListNode head) {
// 左右等分建立左右子树,中间节点作为子树根节点,递归该过程
if (head == null) {
return null;
}
return buildTree(head, 0, getNodeLength(head, 0) - 1);
}
private TreeNode buildTree(ListNode head, int l, int r) {
if (l > r) {
return null;
}
if (l == r) {
return new TreeNode(getNodeVal(head, 0, l));
}
int mid = (l + r) / 2;
TreeNode root = new TreeNode(getNodeVal(head, 0, mid));
root.left = buildTree(head, l, mid - 1);
root.right = buildTree(head, mid + 1, r);
return root;
}
private int getNodeVal(ListNode head, int start, int end) {
if (head == null) {
return 0;
}
if (start == end) {
return head.val;
} else {
return getNodeVal(head.next, start += 1, end);
}
}
private int getNodeLength(ListNode head, int start) {
if (head == null) {
return start;
} else {
return getNodeLength(head.next, start += 1);
}
}
}
48. 旋转图像
class Solution {
public void rotate(int[][] matrix) {
int[][] temp = new int[matrix.length][matrix.length];
int max = matrix.length - 1;
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix.length; j++) {
temp[i][j] = matrix[i][j];
}
}
for (int i = 0; i < temp.length; i++) {
for (int j = 0; j < temp.length; j++) {
matrix[j][max - i] = temp[i][j];
}
}
}
}
806. 写字符串需要的行数
class Solution {
public int[] numberOfLines(int[] widths, String S) {
int[] result = new int[2];
int total = 0;
for (char c : S.toCharArray()) {
if (total + widths[c - 97] > 100) {
result[0]++;
total = widths[c - 97];
} else {
total += widths[c - 97];
}
}
result[1] = total;
if (total != 0) { result[0]++; }
return result;
}
}
521. 最长特殊序列 Ⅰ
class Solution {
public int findLUSlength(String a, String b) {
if (a.equals(b)) {
return -1;
} else {
return Math.max(a.length(), b.length());
}
}
}
118. 杨辉三角
class Solution {
public List<List<Integer>> generate(int numRows) {
List<List<Integer>> result = new ArrayList<>();
if (numRows == 0) {
return result;
}
result.add(Collections.singletonList(1));
if (numRows == 1) {
return result;
}
result.add(Arrays.asList(1, 1));
if (numRows == 2) {
return result;
}
for (int i = 2; i < numRows; i++) {
List<Integer> r = new ArrayList<>();
r.add(1);
List<Integer> preResult = result.get(i - 1);
for (int j = 0; j < preResult.size() - 1; j++) {
r.add(preResult.get(j) + preResult.get(j + 1));
}
r.add(1);
result.add(r);
}
return result;
}
}
682. 棒球比赛
class Solution {
public int calPoints(String[] ops) {
List<Integer> result = new ArrayList<>();
for (int i = 0, j = 0; i < ops.length; i++) {
if (!"CD+".contains(ops[i])) {
result.add(j, Integer.parseInt(ops[i]));
}
if ("C".equals(ops[i])) {
result.remove(--j);
continue;
}
if ("D".equals(ops[i])) {
result.add(j, result.get(j - 1) * 2);
}
if ("+".equals(ops[i])) {
result.add(j, result.get(j - 1) + result.get(j - 2));
}
j++;
}
return result.stream().mapToInt(x -> x).sum();
}
}
349. 两个数组的交集
class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
Set<Integer> set1 = new HashSet<>(nums1.length);
for (int i : nums1) {
set1.add(i);
}
Set<Integer> set2 = new HashSet<>(nums2.length);
for (int i : nums2) {
set2.add(i);
}
set1.retainAll(set2);
int[] result = new int[set1.size()];
int i = 0;
for (Integer integer : set1) {
result[i++] = integer;
}
return result;
}
}
540. 有序数组中的单一元素
class Solution {
public int singleNonDuplicate(int[] nums) {
for (int i = 0; i < nums.length - 2; i += 2) {
if (nums[i] != nums[i + 1]) {return nums[i];}
}
return nums[nums.length - 1];
}
}
289. 生命游戏
class Solution {
public void gameOfLife(int[][] board) {
if (board[0].length == 0) { return; }
int max1 = board.length;
int max2 = board[0].length;
int[][] temp = new int[max1][max2];
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[0].length; j++) {
temp[i][j] = board[i][j];
}
}
for (int i = 0; i < temp.length; i++) {
for (int j = 0; j < temp[0].length; j++) {
int total = 0;
if (i != 0 && j != 0) { total += temp[i - 1][j - 1]; }
if (i != 0) { total += temp[i - 1][j]; }
if (i != 0 && j != max2 - 1) { total += temp[i - 1][j + 1]; }
if (j != 0) { total += temp[i][j - 1]; }
if (j != max2 - 1) { total += temp[i][j + 1]; }
if (i != max1 - 1 && j != 0) { total += temp[i + 1][j - 1]; }
if (i != max1 - 1) { total += temp[i + 1][j]; }
if (i != max1 - 1 && j != max2 - 1) { total += temp[i + 1][j + 1]; }
int ceil = temp[i][j];
if (ceil == 1 && total < 2) {
board[i][j] = 0;
} else if (ceil == 1 && total > 3) {
board[i][j] = 0;
} else if (ceil == 1) {
board[i][j] = 1;
}
if (ceil == 0 && total == 3) {board[i][j] = 1;}
}
}
}
}
64. 最小路径和
class Solution {
public int minPathSum(int[][] grid) {
if (grid == null) { return 0; }
int l = grid.length;
int h = grid[0].length;
int[][] dp = new int[l][h];
for (int i = 0; i < l; i++) {
for (int j = 0; j < h; j++) {
if (i == 0 && j == 0) {
dp[i][j] = grid[0][0];
} else if (i == 0) {
dp[i][j] = dp[i][j - 1] + grid[i][j];
} else if (j == 0) {
dp[i][j] = dp[i - 1][j] + grid[i][j];
} else {
dp[i][j] = Math.min(dp[i - 1][j], dp[i][j - 1]) + grid[i][j];
}
}
}
return dp[l - 1][h - 1];
}
}
463. 岛屿的周长
class Solution {
public int islandPerimeter(int[][] grid) {
int total = 0;
if (grid == null) {
return total;
}
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[0].length; j++) {
int target = grid[i][j];
if (target == 0) { continue; }
try {
if (grid[i][j - 1] == 0) {total += 1;}
} catch (Exception e) {
total += 1;
}
try {
if (grid[i][j + 1] == 0) {total += 1;}
} catch (Exception e) {
total += 1;
}
try {
if (grid[i + 1][j] == 0) {total += 1;}
} catch (Exception e) {
total += 1;
}
try {
if (grid[i - 1][j] == 0) {total += 1;}
} catch (Exception e) {
total += 1;
}
}
}
return total;
}
}
412. Fizz Buzz
class Solution {
public List<String> fizzBuzz(int n) {
List<String> result = new ArrayList<>();
for (int i = 1; i <= n; i++) {
if (i % 15 == 0) {
result.add("FizzBuzz");
} else if (i % 3 == 0) {
result.add("Fizz");
} else if (i % 5 == 0) {
result.add("Buzz");
} else {
result.add(i + "");
}
}
return result;
}
}
566. 重塑矩阵
class Solution {
public int[][] matrixReshape(int[][] nums, int r, int c) {
if (r * c != nums.length * nums[0].length) {return nums;}
int[][] result = new int[r][c];
List<Integer> rs = new ArrayList<>(r * c);
for (int i = 0; i < nums.length; i++) {
for (int j = 0; j < nums[0].length; j++) {
rs.add(nums[i][j]);
}
}
int index = 0;
for (int i = 0; i < result.length; i++) {
for (int j = 0; j < result[0].length; j++) {
result[i][j] = rs.get(index++);
}
}
return result;
}
}
107. 二叉树的层次遍历 II
class Solution {
private List<List<Integer>> result = new ArrayList<>();
private int maxDeep;
public List<List<Integer>> levelOrderBottom(TreeNode root) {
maxDeep = maxDepth(root);
for (int i = 0; i < maxDeep; i++) {
result.add(new ArrayList<>());
}
setResult(root, 0);
return result;
}
public void setResult(TreeNode node, int deep) {
if (node != null) {
deep++;
result.get(maxDeep - deep).add(node.val);
setResult(node.left, deep);
setResult(node.right, deep);
}
}
public int maxDepth(TreeNode root) {
return root == null ? 0 : Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;
}
}
429. N叉树的层序遍历
class Solution {
private List<List<Integer>> result = new ArrayList<>();
public List<List<Integer>> levelOrder(Node root) {
setResult(root, 0);
return result;
}
private void setResult(Node node, int deep) {
if (node == null) { return; }
if (result.size() <= deep) {
result.add(new ArrayList<>());
}
result.get(deep).add(node.val);
deep++;
if (node.children != null) {
for (Node child : node.children) {
setResult(child, deep);
}
}
}
}
575. 分糖果
class Solution {
public int distributeCandies(int[] candies) {
Set<Integer> r = new HashSet<>(candies.length);
for (int candy : candies) {
r.add(candy);
}
return r.size() > candies.length / 2 ? candies.length / 2 : r.size();
}
}
789. 逃脱阻碍者
class Solution {
public boolean escapeGhosts(int[][] ghosts, int[] target) {
int length = Math.abs(target[0]) + Math.abs(target[1]);
for (int i = 0; i < ghosts.length; i++) {
if (Math.abs(target[0] - ghosts[i][0]) + Math.abs(target[1] - ghosts[i][1]) <= length) { return false; }
}
return true;
}
}
496. 下一个更大元素 I
class Solution {
public int[] nextGreaterElement(int[] nums1, int[] nums2) {
for (int i = 0; i < nums1.length; i++) {
int target = nums1[i];
for (int j = 0; j < nums2.length; j++) {
if (nums2[j] == target) {
if (j == nums2.length - 1) {
nums1[i] = -1;
} else {
int max = getMax(nums2, j);
nums1[i] = nums1[i] > max ? -1 : max;
}
break;
}
}
}
return nums1;
}
private int getMax(int[] nums, int start) {
int temp = nums[start];
int result = -1;
for (int i = start + 1; i < nums.length; i++) {
if (temp < nums[i]) {
return nums[i];
}
}
return result;
}
}
876. 链表的中间结点
class Solution {
public ListNode middleNode(ListNode head) {
int max = getMax(head, 1);
int middle = max / 2 + max % 2;
return getListNode(head, middle);
}
private int getMax(ListNode node, int num) {
if (node != null) {
return getMax(node.next, num += 1);
} else {
return num;
}
}
private ListNode getListNode(ListNode head, int start) {
for (int i = 1; i < start; i++) {
head = head.next;
}
return head;
}
}
232. 用栈实现队列
class MyQueue {
Stack<Integer> s = new Stack<Integer>();
Stack<Integer> sQueue = new Stack<Integer>();
/** Initialize your data structure here. */
public MyQueue() {
}
/** Push element x to the back of queue. */
public void push(int x) {
while(!sQueue.isEmpty()) s.push(sQueue.pop());
sQueue.push(x);
while(!s.isEmpty()) sQueue.push(s.pop());
}
/** Removes the element from in front of queue and returns that element. */
public int pop() {
if(sQueue.isEmpty()) return -1;
return sQueue.pop();
}
/** Get the front element. */
public int peek() {
if(sQueue.isEmpty()) return -1;
return sQueue.peek();
}
/** Returns whether the queue is empty. */
public boolean empty() {
return sQueue.isEmpty();
}
}
206. 反转链表
class Solution {
private List<Integer> list = new ArrayList<>();
public ListNode reverseList(ListNode head) {
getMax(head);
setNode(head, list, list.size() - 1);
return head;
}
private void getMax(ListNode node) {
if (node != null) {
list.add(node.val);
getMax(node.next);
}
}
private void setNode(ListNode node, List<Integer> list, int i) {
if (node != null) {
node.val = list.get(i);
setNode(node.next, list, i -= 1);
}
}
}
24. 两两交换链表中的节点
class Solution {
public ListNode swapPairs(ListNode head) {
if (head != null && head.next != null) {
int temp = head.val;
head.val = head.next.val;
head.next.val = temp;
swapPairs(head.next.next);
}
return head;
}
}
148. 排序链表
class Solution {
private List<Integer> list = new ArrayList<>();
public ListNode sortList(ListNode head) {
getList(head);
Collections.sort(list);
setList(head, 0);
return head;
}
private void getList(ListNode node) {
if (node != null) {
list.add(node.val);
getList(node.next);
}
}
private void setList(ListNode node,int num){
if (node != null) {
node.val = list.get(num);
setList(node.next, num += 1);
}
}
}
287. 寻找重复数
class Solution {
public int findDuplicate(int[] nums) {
for (int i = 0; i < nums.length; i++) {
for (int j = 0; j < nums.length; j++) {
if (i == j) {
continue;
}
if (nums[i] == nums[j]) { return nums[i]; }
}
}
return -1;
}
}
12. 整数转罗马数字
class Solution {
private String[][] m = {
{"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"},
{"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"},
{"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"},
{"", "M", "MM", "MMM"}
};
public String intToRoman(int num) {
StringBuilder result = new StringBuilder();
int length = (num + "").length();
for (int i = 0; i < length; i++) {
int r = num % 10;
result.insert(0, m[i][r]);
num /= 10;
}
return result.toString();
}
}
13. 罗马数字转整数
class Solution {
public int romanToInt(String s) {
int total = 0;
Map<Character, Integer> map = new HashMap<>(8);
map.put('I', 1);
map.put('V', 5);
map.put('X', 10);
map.put('L', 50);
map.put('C', 100);
map.put('D', 500);
map.put('M', 1000);
char[] chars = s.toCharArray();
for (int i = 0; i < chars.length - 1; i++) {
if (map.get(chars[i]) < map.get(chars[i + 1])) {
total -= map.get(chars[i]);
} else {
total += map.get(chars[i]);
}
}
total += map.get(chars[chars.length - 1]);
return total;
}
}
893. 特殊等价字符串组
class Solution {
public int numSpecialEquivGroups(String[] A) {
Set<String> set = new HashSet<>();
for (String s : A) {
StringBuilder sb1 = new StringBuilder();
StringBuilder sb2 = new StringBuilder();
char[] chars = s.toCharArray();
for (int i = 0; i < chars.length; i++) {
if (i % 2 == 0) {
sb1.append(chars[i]);
} else {
sb2.append(chars[i]);
}
}
char[] c1 = sb1.toString().toCharArray();
char[] c2 = sb2.toString().toCharArray();
Arrays.sort(c1);
Arrays.sort(c2);
set.add(Arrays.toString(c1) + Arrays.toString(c2));
}
return set.size();
}
}
626. 换座位
select if(id&1 and id = (select count(id) from seat),id, if(id&1,id+1,id-1)) as id, student from seat order by id asc;
136. 只出现一次的数字
class Solution {
public int singleNumber(int[] nums) {
int result = 0;
for (int num : nums) {
result ^= num;
}
return result;
}
}
868. 二进制间距
class Solution {
public int binaryGap(int N) {
String s = Integer.toBinaryString(N);
if (s.indexOf("1") == s.lastIndexOf("1")) {
return 0;
}
//分割后最后一位为1则数组最后少一位,所以补个0
s += 0;
int result = 0;
String[] split = s.split("1");
for (int i = 1; i < split.length - 1; i++) {
if (split[i].length() > result) {result = split[i].length();}
}
result += 1;
return result;
}
}
766. 托普利茨矩阵
class Solution {
public boolean isToeplitzMatrix(int[][] matrix) {
public boolean isToeplitzMatrix(int[][] matrix) {
第一行
//int r = matrix.length, c = matrix[0].length;
//for (int i = 0; i < c; i++) {
// int tmp = matrix[0][i];
// int j = 1, k = i + 1;
//
// while (j < r && k < c) {
// if (matrix[j][k] != tmp) { return false; }
// j++;
// k++;
// }
//}
//
第一列
//for (int i = 1; i < r; i++) {
// int tmp = matrix[i][0];
// int j = i + 1, k = 1;
// while (j < r && k < c) {
// if (matrix[j][k] != tmp) { return false; }
// j++;
// k++;
// }
//}
//return true;
int max1 = matrix.length;
int max2 = matrix[0].length;
if (max2 == 1) {
return true;
}
//纵向
for (int i = 0; i < max1; i++) {
int r = matrix[i][0];
for (int j = 1; j < max1 - i; j++) {
if (j >= max2) {
break;
}
if (r != matrix[j + i][j]) {
return false;
}
}
}
//横向
for (int i = 1; i < max2; i++) {
int r = matrix[0][i];
for (int j = 0; j < max1 - 1; j++) {
if (i + j + 1 >= max2) {
break;
}
if (r != matrix[j + 1][j + i + 1]) {
return false;
}
}
}
return true;
}
}
238. 除自身以外数组的乘积
class Solution {
public int[] productExceptSelf(int[] nums) {
int total = 1;
int flag = 0;
int place = -1;
for (int i = 0; i < nums.length; i++) {
if (nums[i] == 0) {
flag++;
place = i;
} else {
total *= nums[i];
}
}
if (flag == 1) {
for (int i = 0; i < nums.length; i++) {
if (place == i) {
nums[i] = total;
} else {
nums[i] = 0;
}
}
} else if (flag > 1) {
for (int i = 0; i < nums.length; i++) {
nums[i] = 0;
}
} else {
for (int i = 0; i < nums.length; i++) {
nums[i] = total / nums[i];
}
}
return nums;
}
}
144. 二叉树的前序遍历
class Solution {
private List<Integer> result = new ArrayList<>();
public List<Integer> preorderTraversal(TreeNode root) {
getNode(root);
return result;
}
private void getNode(TreeNode node) {
if (node != null) {
result.add(node.val);
getNode(node.left);
getNode(node.right);
}
}
}
637. 二叉树的层平均值
class Solution {
private List<Double> result = new ArrayList<>();
private List<List<Long>> temp = new ArrayList<>();
public List<Double> averageOfLevels(TreeNode root) {
getNode(root, 0);
for (List<Long> r : temp) {
long sum = r.stream().mapToLong(x -> x).sum();
result.add(sum / (double)r.size());
}
return result;
}
private void getNode(TreeNode node, int level) {
if (node != null) {
if (level >= temp.size()) {
temp.add(new ArrayList<>());
}
temp.get(level).add((long)node.val);
level++;
getNode(node.left, level);
getNode(node.right, level);
}
}
}
677. 键值映射
class MapSum {
/**
* Initialize your data structure here.
*/
private Map<String, Integer> result;
public MapSum() {
this.result = new HashMap<>();
}
public void insert(String key, int val) {
result.put(key, val);
}
public int sum(String prefix) {
return result.entrySet().stream().filter(e -> e.getKey().startsWith(prefix)).mapToInt(e -> e.getValue()).sum();
}
}
762. 二进制表示中质数个计算置位
class Solution {
private List<Integer> zs = Arrays.asList(2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47);
public int countPrimeSetBits(int L, int R) {
int total = 0;
for (int i = L; i <= R; i++) {
if (zs.contains(Integer.toBinaryString(i).replace("0", "").length())) {
total++;
}
}
return total;
}
}
9. 回文数
class Solution {
public boolean isPalindrome(int x) {
return (x + "").equals(new StringBuilder(x + "").reverse().toString());
}
}
169. 求众数
class Solution {
public int majorityElement(int[] nums) {
Arrays.sort(nums);
return nums[nums.length / 2];
}
}
215. 数组中的第K个最大元素
class Solution {
public int findKthLargest(int[] nums, int k) {
Arrays.sort(nums);
int count = 1;
for (int i = nums.length - 1; i >= 0; i--) {
if (k == count) {
return nums[i];
} else {
count++;
}
}
return -1;
}
}
120. 三角形最小路径和
class Solution {
public int minimumTotal(List<List<Integer>> triangle) {
for (int i = 1; i < triangle.size(); i++) {
List<Integer> r = triangle.get(i);
for (int j = 0; j < r.size(); j++) {
if (j == 0) {
r.set(j, r.get(j) + triangle.get(i - 1).get(j));
} else if (j == r.size() - 1) {
r.set(j, r.get(j) + triangle.get(i - 1).get(j - 1));
} else {
r.set(j, r.get(j) + Math.min(triangle.get(i - 1).get(j - 1), triangle.get(i - 1).get(j)));
}
}
}
Collections.sort(triangle.get(triangle.size() - 1));
return triangle.get(triangle.size() - 1).get(0);
}
}
129. 求根到叶子节点数字之和
class Solution {
private int total = 0;
public int sumNumbers(TreeNode root) {
if (root == null) {
return 0;
}
getTotal(root, 0);
return total;
}
private void getTotal(TreeNode node, int r) {
r = r * 10 + node.val;
if (node.left == null && node.right == null) {
total += r;
}
if (node.left != null) {
getTotal(node.left, r);
}
if (node.right != null) {
getTotal(node.right, r);
}
}
}
515. 在每个树行中找最大值
class Solution {
private List<Integer> result = new ArrayList<>();
public List<Integer> largestValues(TreeNode root) {
getNode(root, 0);
return result;
}
private void getNode(TreeNode node, int level) {
if (node != null) {
if (result.size() <= level) {
result.add(node.val);
} else {
result.set(level, Math.max(result.get(level), node.val));
}
level++;
getNode(node.left, level);
getNode(node.right, level);
}
}
}
451. 根据字符出现频率排序
class Solution {
public String frequencySort(String s) {
StringBuilder sb = new StringBuilder();
Map<Character, Integer> map = new HashMap<>(s.length());
for (char c : s.toCharArray()) {
if (map.containsKey(c)) {
map.put(c, map.get(c) + 1);
} else {
map.put(c, 1);
}
}
map.entrySet().stream().sorted((x, y) -> y.getValue() - x.getValue()).forEach(e -> {
for (Integer i = 0; i < e.getValue(); i++) {
sb.append(e.getKey());
}
});
return sb.toString();
}
}
739. 每日温度
class Solution {
public int[] dailyTemperatures(int[] T) {
int[] result = new int[T.length];
for (int i = 0; i < T.length; i++) {
int day = 0;
for (int j = i + 1; j < T.length; j++) {
day++;
if (T[i] < T[j]) {
result[i] = day;
break;
}
}
}
return result;
}
}
199. 二叉树的右视图
class Solution {
private List<Integer> result = new ArrayList<>();
public List<Integer> rightSideView(TreeNode root) {
getList(root, 0);
return result;
}
private void getList(TreeNode node, int level) {
if (node != null) {
if (level >= result.size()) {
result.add(node.val);
}
level++;
getList(node.right, level);
getList(node.left, level);
}
}
}
173. 二叉搜索树迭代器
class BSTIterator {
private List<Integer> result = new ArrayList<>();
private Iterator<Integer> iterator;
public BSTIterator(TreeNode root) {
getList(root);
iterator = result.iterator();
}
/**
* @return the next smallest number
*/
public int next() {
return iterator.next();
}
/**
* @return whether we have a next smallest number
*/
public boolean hasNext() {
return iterator.hasNext();
}
private void getList(TreeNode node) {
if (node != null) {
getList(node.left);
result.add(node.val);
getList(node.right);
}
}
}
389. 找不同
class Solution {
public char findTheDifference(String s, String t) {
char[] c1 = s.toCharArray();
char[] c2 = t.toCharArray();
Arrays.sort(c1);
Arrays.sort(c2);
int l1 = c1.length;
int l2 = c2.length;
if (l1 > l2) {
for (int i = 0; i < l2; i++) {
if (c1[i] != c2[i]) {
return c1[i];
}
}
return c1[l1 - 1];
}
for (int i = 0; i < l1; i++) {
if (c1[i] != c2[i]) {
return c2[i];
}
}
return c2[l2 - 1];
}
}
147. 对链表进行插入排序
class Solution {
private List<Integer> list = new ArrayList<>();
public ListNode insertionSortList(ListNode head) {
setList(head);
Collections.sort(list);
sortList(head, 0);
return head;
}
private void setList(ListNode node) {
if (node != null) {
list.add(node.val);
setList(node.next);
}
}
private void sortList(ListNode node, int index) {
if (node != null) {
node.val = list.get(index);
sortList(node.next, index += 1);
}
}
}
318. 最大单词长度乘积
class Solution {
public int maxProduct(String[] words) {
return getMax(words);
}
private int getMax(String[] words) {
Set<Character> s1 = new HashSet<>();
Set<Character> s2 = new HashSet<>();
int max = 0;
for (int i = 0; i < words.length; i++) {
for (char c : words[i].toCharArray()) {
s1.add(c);
}
int m1 = s1.size();
for (int j = i + 1; j < words.length; j++) {
for (char c : words[j].toCharArray()) {
s2.add(c);
}
int m2 = s2.size();
int m;
if (m1 > m2) {
s1.retainAll(s2);
m = s1.size();
s1.clear();
for (char c : words[i].toCharArray()) {
s1.add(c);
}
m1 = s1.size();
} else {
s2.retainAll(s1);
m = s2.size();
}
if (m == 0) {
//长度减去交集的长度为最大长度
max = Math.max(max, words[i].length() * words[j].length());
}
s2.clear();
}
s1.clear();
}
return max;
}
}
347. 前K个高频元素
class Solution {
public List<Integer> topKFrequent(int[] nums, int k) {
List<Integer> result = new ArrayList<>();
Map<Integer, Integer> map = new HashMap<>(nums.length);
for (int i = 0; i < nums.length; i++) {
if (map.containsKey(nums[i])) {
map.put(nums[i], map.get(nums[i]) + 1);
} else {
map.put(nums[i], 1);
}
}
map.entrySet().stream().sorted((x, y) -> y.getValue() - x.getValue()).forEach(e -> {
if (result.size() < k) {
result.add(e.getKey());
}
});
return result;
}
}
328. 奇偶链表
class Solution {
private List<Integer> l1 = new ArrayList<>();
private List<Integer> l2 = new ArrayList<>();
public ListNode oddEvenList(ListNode head) {
setList(head, 1);
l1.addAll(l2);
setNode(head, 0);
return head;
}
private void setList(ListNode node, int level) {
if (node != null) {
if (level % 2 == 1) {
l1.add(node.val);
} else {
l2.add(node.val);
}
setList(node.next, level += 1);
}
}
private void setNode(ListNode node, int level) {
if (node != null) {
node.val = l1.get(level);
setNode(node.next, level += 1);
}
}
}
119. 杨辉三角 II
class Solution {
public List<Integer> getRow(int rowIndex) {
List<List<Integer>> result = new ArrayList<>();
result.add(Collections.singletonList(1));
if (rowIndex == 0) {
return result.get(rowIndex);
}
result.add(Arrays.asList(1, 1));
if (rowIndex == 1) {
return result.get(rowIndex);
}
for (int i = 2; i <= rowIndex; i++) {
List<Integer> r = new ArrayList<>();
r.add(1);
List<Integer> preResult = result.get(i - 1);
for (int j = 0; j < preResult.size() - 1; j++) {
r.add(preResult.get(j) + preResult.get(j + 1));
}
r.add(1);
result.add(r);
}
return result.get(rowIndex);
}
}
841. 钥匙和房间
class Solution {
public boolean canVisitAllRooms(List<List<Integer>> rooms) {
List<Integer> keys = rooms.get(0);
Set<Integer> s = new HashSet<>(keys);
for (int i = 0; i < rooms.size(); i++) {
Set<Integer> temp = new HashSet<>(s);
for (Integer index : s) {
temp.addAll(rooms.get(index));
}
s = temp;
}
s.remove(0);
return rooms.size() == s.size() + 1;
}
}
27. 移除元素
class Solution {
public int removeElement(int[] nums, int val) {
int count = 0;
int l = nums.length;
for (int i = 0; i < l; i++) {
if (val == nums[i]) {
for (int j = i; j < l - 1; j++) {
int temp = nums[j];
nums[j] = nums[j + 1];
nums[j + 1] = temp;
}
count++;
l--;
i--;
}
}
return nums.length - count;
}
}
824. 山羊拉丁文
class Solution {
public String toGoatLatin(String S) {
StringBuilder sb = new StringBuilder();
String[] strs = S.split(" ");
for (int i = 1; i <= strs.length; i++) {
String s = strs[i - 1].toLowerCase();
if ("aeiou".contains(s.charAt(0) + "")) {
sb.append(strs[i - 1]).append("ma");
} else {
sb.append(strs[i - 1].substring(1) + strs[i - 1].charAt(0)).append("ma");
}
for (int j = 0; j < i; j++) {
sb.append("a");
}
sb.append(" ");
}
return sb.toString().trim();
}
}
102. 二叉树的层次遍历
class Solution {
List<List<Integer>> result = new ArrayList<>();
public List<List<Integer>> levelOrder(TreeNode root) {
setList(root, 0);
return result;
}
private void setList(TreeNode node, int level) {
if (node != null) {
if (level >= result.size()) {
result.add(new ArrayList<>());
}
result.get(level).add(node.val);
level++;
setList(node.left, level);
setList(node.right, level);
}
}
}
884. 两句话中的不常见单词
class Solution {
public String[] uncommonFromSentences(String A, String B) {
String[] s1 = A.split(" ");
String[] s2 = B.split(" ");
Map<String, Integer> map = new HashMap<>(s1.length + s2.length);
for (String s : s1) {
map.put(s, map.containsKey(s) ? map.get(s) + 1 : 1);
}
for (String s : s2) {
map.put(s, map.containsKey(s) ? map.get(s) + 1 : 1);
}
List<String> c = map.entrySet().stream().filter(e -> e.getValue() == 1).map(e -> e.getKey()).collect(
Collectors.toList());
String[] result = new String[c.size()];
c.toArray(result);
return result;
}
}
378. 有序矩阵中第K小的元素
class Solution {
public int kthSmallest(int[][] matrix, int k) {
List<Integer> list = new ArrayList<>();
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[0].length; j++) {
list.add(matrix[i][j]);
}
}
Collections.sort(list);
return list.get(k - 1);
}
}
283. 移动零
class Solution {
public void moveZeroes(int[] nums) {
int l = nums.length;
for (int i = 0; i < l; i++) {
if (nums[i] == 0) {
for (int j = i; j < l - 1; j++) {
int temp = nums[j];
nums[j] = nums[j + 1];
nums[j + 1] = temp;
}
l--;
i--;
}
}
}
}
937. 重新排列日志文件
class Solution {
public String[] reorderLogFiles(String[] logs) {
String num = "0123456789";
List<String> l1 = new ArrayList<>();
List<String> l2 = new ArrayList<>();
for (String log : logs) {
if (num.contains(log.split(" ")[1].charAt(0) + "")) {
l2.add(log);
} else {
l1.add(log);
}
}
l1.sort((x, y) -> {
x = x.substring(x.indexOf(" "));
y = y.substring(y.indexOf(" "));
return x.compareTo(y);
});
l1.addAll(l2);
l1.toArray(logs);
return logs;
}
}
485. 最大连续1的个数
class Solution {
public int findMaxConsecutiveOnes(int[] nums) {
int total = 0;
int temp = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i] == 0) {
total = Math.max(temp, total);
temp = 0;
continue;
}
temp++;
}
total = Math.max(temp, total);
return total;
}
}
21. 合并两个有序链表
class Solution {
private List<Integer> list = new ArrayList<>();
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if (l1 == null && l2 == null) {
return null;
}
setList(l1);
setList(l2);
Collections.sort(list);
ListNode r = new ListNode(list.get(0));
if (list.size() == 1) {
return r;
}
getList(r, 1);
return r;
}
private void setList(ListNode node) {
if (node != null) {
list.add(node.val);
setList(node.next);
}
}
private void getList(ListNode node, int level) {
node.next = new ListNode(list.get(level));
if (level != list.size() - 1) {
getList(node.next, level += 1);
}
}
}