《LeetCode 热题 HOT 100》Java答案汇总版
个人认为《LeetCode 热题 HOT 100》中的题目特别适合算法新手进行一个入门的刷题,而且作者做了一半左右的题目就感觉收获颇丰,可以拿一些编程大赛的国家级三等奖了,是刷算法题的不二选择!!!
官方题目链接:https://leetcode.cn/problem-list/2cktkvj/
Java代码:
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.util.*;
class ListNode {
int val;
ListNode next;
ListNode() {
}
ListNode(int val) {
this.val = val;
}
ListNode(int val, ListNode next) {
this.val = val;
this.next = next;
}
}
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode() {
}
TreeNode(int val) {
this.val = val;
}
TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
public class LeetCode {
public void NarcissisticNumber() {
Scanner in = new Scanner(System.in);
String nums = "";
ArrayList<Integer> result = new ArrayList<>();
int m = 0;
int n = 0;
while (in.hasNext()) {
result.clear();
nums = in.nextLine();
m = Integer.parseInt(nums.split(" ")[0]);
n = Integer.parseInt(nums.split(" ")[1]);
int a, b, c = 0;
for (int i = m; i <= n; i++) {
a = i / 100;
b = (i - a * 100) / 10;
c = i - a * 100 - b * 10;
if (i == a * a * a + b * b * b + c * c * c) {
result.add(i);
}
}
if (result.size() == 0) {
System.out.println("no");
continue;
}
for (int i = 0; i < result.size(); i++) {
if (i == result.size() - 1) {
System.out.println(result.get(i));
} else {
System.out.print(result.get(i) + " ");
}
}
}
}
public boolean exist(char[][] board, String word) {
int h = board.length;
int w = board[0].length;
boolean[][] visited = new boolean[h][w];
for (int i = 0; i < h; i++) {
for (int j = 0; j < w; j++) {
boolean flag = check(board, visited, i, j, word, 0);
if (flag) {
return true;
}
}
}
return false;
}
private boolean check(char[][] board, boolean[][] visited, int i, int j, String word, int index) {
if (board[i][j] != word.charAt(index)) {
return false;
} else if (index == word.length() - 1) {
return true;
}
visited[i][j] = true;
int[][] directions = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
boolean result = false;
for (int[] go : directions) {
int newI = i + go[0];
int newJ = j + go[1];
if (newI >= 0 && newJ >= 0 && newI < board.length && newJ < board[0].length) {
if (!visited[newI][newJ]) {
boolean flag = check(board, visited, newI, newJ, word, index + 1);
if (flag) {
result = true;
break;
}
}
}
}
visited[i][j] = false;
return result;
}
public boolean canJump(int[] nums) {
int n = nums.length;
int max = 0;
for (int i = 0; i <= max; i++) {
max = Math.max(max, i + nums[i]);
if (max >= n - 1) {
return true;
}
}
return false;
}
public List<List<Integer>> permute(int[] nums) {
List<List<Integer>> result = new ArrayList<>();
List<Integer> combine = new ArrayList<>();
for (int num : nums) {
combine.add(num);
}
backTrack(result, combine, nums.length, 0);
return result;
}
private void backTrack(List<List<Integer>> result, List<Integer> combine, int length, int index) {
if (index == length) {
result.add(new ArrayList<>(combine));
}
for (int i = index; i < length; i++) {
Collections.swap(combine, index, i);
backTrack(result, combine, length, index + 1);
Collections.swap(combine, index, i);
}
}
public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> result = new ArrayList<>();
List<Integer> combine = new ArrayList<>();
backTrack(candidates, target, result, combine, 0);
return result;
}
private void backTrack(int[] candidates, int target, List<List<Integer>> result, List<Integer> combine, int index) {
if (index == candidates.length) {
return;
}
if (target == 0) {
result.add(new ArrayList<>(combine));
return;
}
backTrack(candidates, target, result, combine, index + 1);
if (target - candidates[index] >= 0) {
combine.add(candidates[index]);
backTrack(candidates, target - candidates[index], result, combine, index);
combine.remove(combine.size() - 1);
}
}
public List<String> generateParenthesis(int n) {
List<String> result = new ArrayList<>();
backTrack(result, new StringBuffer(), 0, 0, n);
return result;
}
private void backTrack(List<String> result, StringBuffer stringBuffer, int open, int close, int max) {
if (stringBuffer.length() == (max * 2)) {
result.add(stringBuffer.toString());
return;
}
if (open < max) {
stringBuffer.append('(');
backTrack(result, stringBuffer, open + 1, close, max);
stringBuffer.deleteCharAt(stringBuffer.length() - 1);
}
if (close < open) {
stringBuffer.append(')');
backTrack(result, stringBuffer, open, close + 1, max);
stringBuffer.deleteCharAt(stringBuffer.length() - 1);
}
}
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode fake = new ListNode();
fake.next = head;
ListNode p1 = fake;
ListNode p2 = head;
for (int i = 0; i < n; i++) {
p2 = p2.next;
}
while (p2 != null) {
p1 = p1.next;
p2 = p2.next;
}
if (p1.next != null) {
p1.next = p1.next.next;
}
return fake.next;
}
public ListNode removeNthFromEnd(ListNode head, int n) {
if (head == null) {
return null;
}
int length = 0;
ListNode p1 = head;
while (p1 != null) {
length++;
p1 = p1.next;
}
if (length == n) {
return head.next;
}
int index = 0;
ListNode p2 = head;
while (index != (length - n - 1)) {
index++;
p2 = p2.next;
}
p2.next = p2.next.next;
return head;
}
public List<String> letterCombinations(String digits) {
List<String> result = new ArrayList<>();
if (digits.length() == 0) {
return result;
}
HashMap<Character, String> map = new HashMap<>();
map.put('2', "abc");
map.put('3', "def");
map.put('4', "ghi");
map.put('5', "jkl");
map.put('6', "mno");
map.put('7', "pqrs");
map.put('8', "tuv");
map.put('9', "wxyz");
backTrack(result, map, digits, 0, new StringBuffer());
return result;
}
private void backTrack(List<String> result, HashMap<Character, String> map, String digits, int i, StringBuffer stringBuffer) {
if (i == digits.length()) {
result.add(stringBuffer.toString());
} else {
char digit = digits.charAt(i);
String letters = map.get(digit);
int letterNum = letters.length();
for (int index = 0; index < letterNum; index++) {
stringBuffer.append(letters.charAt(index));
backTrack(result, map, digits, i + 1, stringBuffer);
stringBuffer.deleteCharAt(i);
}
}
}
public int[] arraySort(int[] num) {
int temp = 0;
for (int i = 1; i < num.length; i++) {
boolean flag = true;
for (int j = 0; j < num.length - i; j++) {
if (num[j] >= num[j + 1]) {
temp = num[j];
num[j] = num[j + 1];
num[j + 1] = temp;
flag = false;
}
}
if (flag) {
break;
}
}
return num;
}
public List<List<Integer>> threeSum(int[] nums) {
int n = nums.length;
Arrays.sort(nums);
List<List<Integer>> result = new ArrayList<>();
for (int first = 0; first < n; first++) {
if (first > 0 && nums[first] == nums[first - 1]) {
continue;
}
int third = n - 1;
int target = -nums[first];
for (int second = first + 1; second < n; second++) {
if (second > first + 1 && nums[second] == nums[second - 1]) {
continue;
}
while (second < third && (nums[second] + nums[third]) > target) {
third--;
}
if (second == third) {
break;
}
if (nums[second] + nums[third] == target) {
ArrayList<Integer> list = new ArrayList<>();
list.add(nums[first]);
list.add(nums[second]);
list.add(nums[third]);
result.add(list);
}
}
}
return result;
}
public int maxArea(int[] height) {
int result = 0;
int p1 = 0;
int p2 = height.length - 1;
while (p1 < p2) {
result = Math.max(result, Math.min(height[p1], height[p2]) * (p2 - p1));
if (height[p1] <= height[p2]) {
p1++;
} else {
p2--;
}
}
return result;
}
public int maxArea(int[] height) {
int n = height.length;
int result = 0;
int temp = 0;
for (int i = 0; i < n; i++) {
for (int j = i; j < n; j++) {
temp = Math.min(height[i], height[j]);
result = Math.max(result, temp * (j - i));
}
}
return result;
}
public String longestPalindrome(String s) {
int len = s.length();
if (len < 2) {
return s;
}
int maxLen = 1;
int begin = 0;
boolean[][] dp = new boolean[len][len];
for (int i = 0; i < len; i++) {
dp[i][i] = true;
}
char[] charArray = s.toCharArray();
for (int L = 2; L <= len; L++) {
for (int i = 0; i < len; i++) {
int j = L + i - 1;
if (j >= len) {
break;
}
if (charArray[i] != charArray[j]) {
dp[i][j] = false;
} else {
if (j - i < 3) {
dp[i][j] = true;
} else {
dp[i][j] = dp[i + 1][j - 1];
}
}
if (dp[i][j] && L > maxLen) {
maxLen = L;
begin = i;
}
}
}
return s.substring(begin, begin + maxLen);
}
public int lengthOfLongestSubstring(String s) {
int result = 0;
HashSet<Character> ch = new HashSet<>();
int n = s.length();
int p2 = -1;
for (int i = 0; i < n; i++) {
if (i != 0) {
ch.remove(s.charAt(i - 1));
}
while ((p2 + 1) < n && !ch.contains(s.charAt(p2 + 1))) {
ch.add(s.charAt(p2 + 1));
p2++;
}
result = Math.max(result, p2 - i + 1);
}
return result;
}
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode result = null;
ListNode p1 = null;
int carry = 0;
int x = 0;
int y = 0;
int temp = 0;
while (l1 != null || l2 != null) {
if (result == null) {
result = new ListNode();
p1 = result;
} else {
p1.next = new ListNode();
p1 = p1.next;
}
x = l1 == null ? 0 : l1.val;
y = l2 == null ? 0 : l2.val;
temp = x + y + carry;
carry = 0;
if (temp > 9) {
carry = 1;
}
temp = temp % 10;
p1.val = temp;
p1.next = null;
l1 = l1 == null ? null : l1.next;
l2 = l2 == null ? null : l2.next;
}
if (carry == 1) {
p1.next = new ListNode();
p1 = p1.next;
p1.val = 1;
}
return result;
}
public TreeNode mergeTrees(TreeNode root1, TreeNode root2) {
if (root1 == null) {
return root2;
}
if (root2 == null) {
return root1;
}
TreeNode merged = new TreeNode(root1.val + root2.val);
merged.left = mergeTrees(root1.left, root2.left);
merged.right = mergeTrees(root1.right, root2.right);
return merged;
}
private int result = 0;
public int diameterOfBinaryTree(TreeNode root) {
maxDepth(root);
return result - 1;
}
private int maxDepth(TreeNode root) {
if (root == null) {
return 0;
}
int left = maxDepth(root.left);
int right = maxDepth(root.right);
result = Math.max(result, left + right + 1);
return Math.max(left, right) + 1;
}
public int hammingDistance(int x, int y) {
int result = x ^ y;
int count = 0;
while (result != 0) {
result = result & (result - 1);
count++;
}
return count;
}
public int hammingDistance(int x, int y) {
return Integer.bitCount(x ^ y);
}
public List<Integer> findDisappearedNumbers(int[] nums) {
int n = nums.length;
int temp = 0;
ArrayList<Integer> result = new ArrayList<>();
for (int num : nums) {
temp = (num - 1) % n;
nums[temp] = nums[temp] + n;
}
for (int i = 0; i < n; i++) {
if (nums[i] <= n) {
result.add(i + 1);
}
}
return result;
}
public List<Integer> findDisappearedNumbers(int[] nums) {
int n = nums.length;
int[] index = new int[n + 1];
ArrayList<Integer> result = new ArrayList<>();
for (int num : nums) {
index[num] = 1;
}
for (int i = 1; i <= n; i++) {
if (index[i] != 1) {
result.add(i);
}
}
return result;
}
public int[] countBits(int n) {
int[] result = new int[n + 1];
int counts = 0;
for (int i = 0; i <= n; i++) {
int temp = i;
counts = 0;
while (temp != 0) {
temp = temp & (temp - 1);
counts++;
}
result[i] = counts;
}
return result;
}
public int[] countBits(int n) {
int[] nums = new int[n + 1];
for (int i = 0; i <= n; i++) {
nums[i] = Integer.bitCount(i);
}
return nums;
}
public void moveZeroes(int[] nums) {
int p1 = 0;
int p2 = 0;
while (p2 <= nums.length - 1) {
if (nums[p2] != 0) {
swap(nums, p1, p2);
p1++;
}
p2++;
}
}
private void swap(int[] nums, int p1, int p2) {
int temp = nums[p2];
nums[p2] = nums[p1];
nums[p1] = temp;
}
public void moveZeroes(int[] nums) {
int index = 0;
for (int num : nums) {
if (num != 0) {
nums[index] = num;
index++;
}
}
for (int i = index; i < nums.length; i++) {
nums[i] = 0;
}
}
public boolean isPalindrome(ListNode head) {
if (head == null) {
return true;
}
ListNode firstHalfEnd = findHalf(head);
ListNode secondHalfStart = reverseList(firstHalfEnd.next);
ListNode p1 = head;
ListNode p2 = secondHalfStart;
while (p2 != null) {
if (p1.val != p2.val) {
firstHalfEnd.next = reverseList(secondHalfStart);
return false;
}
p1 = p1.next;
p2 = p2.next;
}
firstHalfEnd.next = reverseList(secondHalfStart);
return true;
}
private ListNode reverseList(ListNode head) {
if (head == null) {
return null;
}
ListNode p1 = null;
ListNode p2 = head;
ListNode temp = null;
while (p2 != null) {
temp = p2.next;
p2.next = p1;
p1 = p2;
p2 = temp;
}
return p1;
}
private ListNode findHalf(ListNode head) {
if (head == null) {
return null;
}
ListNode p1 = head;
ListNode p2 = head;
while (p2.next != null && p2.next.next != null) {
p1 = p1.next;
p2 = p2.next.next;
}
return p1;
}
public boolean isPalindrome(ListNode head) {
ArrayList<Integer> nums = new ArrayList<>();
while (head != null) {
nums.add(head.val);
head = head.next;
}
int p1 = 0;
int p2 = nums.size() - 1;
while (p1 < p2) {
if (!nums.get(p1).equals(nums.get(p2))) {
return false;
}
p1++;
p2--;
}
return true;
}
public TreeNode invertTree(TreeNode root) {
if (root == null) {
return null;
}
TreeNode left = invertTree(root.left);
TreeNode right = invertTree(root.right);
root.right = left;
root.left = right;
return root;
}
public ListNode reverseList(ListNode head) {
if (head == null) {
return null;
}
ListNode p1 = null;
ListNode p2 = head;
ListNode temp = null;
while (p2 != null) {
temp = p2.next;
p2.next = p1;
p1 = p2;
p2 = temp;
}
return p1;
}
public ListNode reverseList(ListNode head) {
if (head == null) {
return null;
}
ListNode result = null;
for (ListNode i = head; i != null; i = i.next) {
result = new ListNode(i.val, result);
}
return result;
}
public int majorityElement(int[] nums) {
int count = 0;
int candidate = 0;
for (int num : nums) {
if (count == 0) {
candidate = num;
count++;
} else {
count = count + (num == candidate ? 1 : -1);
}
}
return candidate;
}
public int majorityElement(int[] nums) {
Arrays.sort(nums);
return nums[nums.length/2];
}
public int majorityElement(int[] nums) {
int n = nums.length;
HashMap<Integer, Integer> map = new HashMap<>();
for (int num : nums) {
int a = map.getOrDefault(num, 0) + 1;
if (a > n / 2) {
return num;
}
map.put(num, a);
}
return -1;
}
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
ListNode p1 = headA;
ListNode p2 = headB;
while (p1 != p2) {
if (p1 == null) {
p1 = headB;
} else {
p1 = p1.next;
}
if (p2 == null) {
p2 = headA;
} else {
p2 = p2.next;
}
}
return p1;
}
public boolean hasCycle(ListNode head) {
if (head == null || head.next == null) {
return false;
}
ListNode p1 = head;
ListNode p2 = head.next;
while (p1 != p2) {
if (p2 == null || p2.next == null) {
return false;
}
p1 = p1.next;
p2 = p2.next.next;
}
return true;
}
public int singleNumber(int[] nums) {
int result = 0;
for (int num : nums) {
result = result ^ num;
}
return result;
}
public int singleNumber(int[] nums) {
ArrayList<Integer> set = new ArrayList<>();
for (int num : nums) {
if (set.contains(num)){
set.remove((Integer) num);
}else {
set.add(num);
}
}
return set.get(0);
}
public int maxProfit(int[] prices) {
int minPrice = Integer.MAX_VALUE;
int result = 0;
for (int i = 0; i < prices.length; i++) {
minPrice = Math.min(prices[i], minPrice);
result = Math.max(result, prices[i] - minPrice);
}
return result;
}
public int maxProfit(int[] prices) {
int n = prices.length;
int result = 0;
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
int temp = prices[j] - prices[i];
result=Math.max(result,temp);
}
}
return result;
}
public int maxDepth(TreeNode root) {
if (root == null) {
return 0;
}
int leftDepth = maxDepth(root.left);
int rightDepth = maxDepth(root.right);
return Math.max(leftDepth, rightDepth) + 1;
}
public boolean isSymmetric(TreeNode root) {
return check(root.left, root.right);
}
private boolean check(TreeNode left, TreeNode right) {
if (left == null && right == null) {
return true;
}
if (left == null || right == null) {
return false;
}
return left.val == right.val && check(left.right, right.left) && check(left.left, right.right);
}
public List<Integer> inorderTraversal(TreeNode root) {
ArrayList<Integer> result = new ArrayList<>();
ArrayDeque<TreeNode> stack = new ArrayDeque<>();
while (root != null || !stack.isEmpty()) {
while (root != null) {
stack.push(root);
root = root.left;
}
root = stack.pop();
result.add(root.val);
root = root.right;
}
return result;
}
public List<Integer> inorderTraversal(TreeNode root) {
ArrayList<Integer> result = new ArrayList<>();
inOrder(root, result);
return result;
}
private void inOrder(TreeNode root, ArrayList<Integer> result) {
if (root == null) {
return;
}
inOrder(root.left, result);
result.add(root.val);
inOrder(root.right, result);
}
public int climbStairs(int n) {
if (n == 1) {
return 1;
}
if (n == 2) {
return 2;
}
int p = 1;
int q = 2;
int result = 0;
for (int i = 3; i <= n; i++) {
result = p + q;
p = q;
q = result;
}
return result;
}
public int climbStairs(int n) {
if (n == 0) {
return 0;
}
if (n == 1) {
return 1;
}
if (n == 2) {
return 2;
}
return climbStairs(n - 1) + climbStairs(n - 2);
}
public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
if (list1 == null) {
return list2;
}
if (list2 == null) {
return list1;
}
ListNode result = new ListNode();
ListNode ptr = result;
while (list1 != null && list2 != null) {
ListNode node = new ListNode();
if (list1.val <= list2.val) {
ptr.val = list1.val;
list1 = list1.next;
} else {
ptr.val = list2.val;
list2 = list2.next;
}
ptr.next = node;
ptr = node;
}
if (list1 == null) {
ptr.val = list2.val;
ptr.next = list2.next;
}
if (list2 == null) {
ptr.val = list1.val;
ptr.next = list1.next;
}
return result;
}
public boolean isValid(String s) {
if (s.length() % 2 == 1) {
return false;
}
ArrayDeque<Character> stack = new ArrayDeque<>();
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
if (ch == '(' || ch == '{' || ch == '[') {
stack.push(ch);
}
if (ch == ')') {
if (stack.isEmpty() || stack.peek() != '(') {
return false;
}
stack.pop();
}
if (ch == ']') {
if (stack.isEmpty() || stack.peek() != '[') {
return false;
}
stack.pop();
}
if (ch == '}') {
if (stack.isEmpty() || stack.peek() != '{') {
return false;
}
stack.pop();
}
}
return stack.isEmpty();
}
public int[] twoSum(int[] nums, int target) {
HashMap<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
if (map.containsKey(target - nums[i])) {
return new int[]{i, map.get(target - nums[i])};
}
map.put(nums[i], i);
}
return new int[]{-1};
}
}