字符串

无重复字符的最长子串(3)- 543

  1. // https://leetcode.cn/problems/longest-substring-without-repeating-characters/
  2. // 给定一个字符串 s ,请你找出其中不含有重复字符的 最长子串 的长度
  3. // 输入: s = "abcabcbb"
  4. // 输出: 3
  5. // 解释: 因为无重复字符的最长子串是 "abc",所以其长度为 3
  6. // 输入: s = "bbbbb"
  7. // 输出: 1
  8. // 解释: 因为无重复字符的最长子串是 "b",所以其长度为 1
  9. class Solution {
  10. // 滑动窗口
  11. public int lengthOfLongestSubstring(String s) {
  12. // 窗口的最大长度
  13. int maxLength = 0;
  14. // 窗口集合
  15. Set<Character> window = new HashSet<>();
  16. int left = 0; // 窗口的左边界
  17. int right = 0; // 窗口的右边界
  18. while (right < s.length()) {
  19. // 如果窗口中包含当前元素,说明出现了重复,
  20. // 把窗口最左端的给移除掉,直到窗口不包含当前元素即可
  21. while (window.contains(s.charAt(right))){
  22. window.remove(s.charAt(left));
  23. left++;
  24. }
  25. // 把当前元素添加到窗口中
  26. window.add(s.charAt(right));
  27. // 更新窗口的长度
  28. maxLength = Math.max(maxLength, right - left + 1);
  29. right++;
  30. }
  31. return maxLength;
  32. }
  33. // 使用队列
  34. public int lengthOfLongestSubstring2(String s) {
  35. // 创建队列
  36. Queue<Character> queue = new LinkedList<>();
  37. int maxLength = 0;
  38. for (char ch : s.toCharArray()) {
  39. // 如果队列中有重复的就把最先添加的字符给移除,
  40. // 直到队列中没有重复元素为止
  41. while (queue.contains(ch))
  42. queue.poll();
  43. // 把当前字符添加到队列中
  44. queue.add(ch);
  45. // 记录最大值
  46. maxLength = Math.max(maxLength, queue.size());
  47. }
  48. return maxLength;
  49. }
  50. }

最长回文子串(5)- 188

  1. // https://leetcode.cn/problems/longest-palindromic-substring/
  2. // 给你一个字符串 s,找到 s 中最长的回文子串。
  3. // 如果字符串的反序与原始字符串相同,则该字符串称为回文字符串
  4. // 输入:s = "babad"
  5. // 输出:"bab"
  6. // 解释:"aba" 同样是符合题意的答案
  7. // 输入:s = "cbbd"
  8. // 输出:"bb"
  9. class Solution {
  10. // 暴力解法:时间复杂度:两层for循环O(n²),for循环里边判断是否为回文O(n),所以时间复杂度为O(n³)
  11. // 空间复杂度:O(1),常数个变量
  12. public String longestPalindrome(String s) {
  13. String ans = "";
  14. int max = 0;
  15. int len = s.length();
  16. for (int i = 0; i < len; i++)
  17. for (int j = i + 1; j <= len; j++) {
  18. String test = s.substring(i, j);
  19. if (isPalindromic(test) && test.length() > max) {
  20. ans = s.substring(i, j);
  21. max = Math.max(max, ans.length());
  22. }
  23. }
  24. return ans;
  25. }
  26. public boolean isPalindromic(String s) {
  27. int len = s.length();
  28. for (int i = 0; i < len / 2; i++) {
  29. if (s.charAt(i) != s.charAt(len - i - 1)) {
  30. return false;
  31. }
  32. }
  33. return true;
  34. }
  35. }

22222 最长回文串(409)- 6

  1. // https://leetcode.cn/problems/longest-palindrome/
  2. // 给定一个包含大写字母和小写字母的字符串 s ,返回 通过这些字母构造成的 最长的回文串 。
  3. // 在构造过程中,请注意 区分大小写 。比如 "Aa" 不能当做一个回文字符串
  4. // 输入:s = "abccccdd"
  5. // 输出:7
  6. // 解释:
  7. // 我们可以构造的最长的回文串是"dccaccd", 它的长度是 7
  8. // 输入:s = "a"
  9. // 输入:1
  10. class Solution {
  11. public static int longestPalindrome(String s) {
  12. int res = 0;
  13. // set存放字符个数为奇数的字符
  14. Set<Character> set = new HashSet<>();
  15. for (int i = 0; i < s.length(); i++) {
  16. char c = s.charAt(i);
  17. // 若字符在集合中存在,则删除集合中的元素,同时不向集合中添加该元素(表明该元素的个数为偶数)
  18. if (!set.remove(c)) {
  19. set.add(c);
  20. }
  21. }
  22. // set.size() == 0表示整个字符串都是回文字符串
  23. // s.length() - set.size() + 1表示剔除奇数个字符后,所有偶数字符的个数,最后加上一个奇数字符放最中间
  24. return set.size() == 0 ? s.length() : s.length() - set.size() + 1;
  25. }
  26. }

字符串相加(415)- 148

  1. // https://leetcode.cn/problems/add-strings/
  2. // 给定两个字符串形式的非负整数 num1 和num2 ,计算它们的和并同样以字符串形式返回。
  3. // 你不能使用任何內建的用于处理大整数的库(比如 BigInteger), 也不能直接将输入的字符串转换为整数形式。
  4. // 输入:num1 = "11", num2 = "123"
  5. // 输出:"134"
  6. // 输入:num1 = "456", num2 = "77"
  7. // 输出:"533"
  8. class Solution {
  9. public String addStrings(String num1, String num2) {
  10. // 指针i指向num1的末尾
  11. int i = num1.length() - 1;
  12. // 指针j指向num2的末尾
  13. int j = num2.length() - 1;
  14. // add 维护当前是否有进位
  15. int add = 0;
  16. StringBuffer ans = new StringBuffer();
  17. while (i >= 0 || j >= 0 || add != 0) {
  18. // 获取num1第i位置上的字符,通过-'0',转换为int
  19. int x = i >= 0 ? num1.charAt(i) - '0' : 0;
  20. int y = j >= 0 ? num2.charAt(j) - '0' : 0;
  21. int result = x + y + add;
  22. // ans只保留个位数
  23. ans.append(result % 10);
  24. // add表示十位数,要向后进位
  25. add = result / 10;
  26. // num1和num2都向前移
  27. i--;
  28. j--;
  29. }
  30. // 计算完以后的答案需要翻转过来
  31. ans.reverse();
  32. return ans.toString();
  33. }
  34. }

0 - 最长公共子序列(1143)- 97

  1. // https://leetcode.cn/problems/longest-common-subsequence/description/
  2. // 给定两个字符串 text1 和 text2,返回这两个字符串的最长 公共子序列 的长度。如果不存在 公共子序列 ,返回 0
  3. // 一个字符串的 子序列 是指这样一个新的字符串:它是由原字符串在不改变字符的相对顺序的情况下删除某些字符(也可以不删除任何字符)后组成的新字符串
  4. // 例如,"ace" 是 "abcde" 的子序列,但 "aec" 不是 "abcde" 的子序列
  5. // 输入:text1 = "abcde", text2 = "ace"
  6. // 输出:3
  7. // 解释:最长公共子序列是 "ace" ,它的长度为 3
  8. class Solution {
  9. public int longestCommonSubsequence(String text1, String text2) {
  10. int m = text1.length(), n = text2.length();
  11. // dp[i][j]表示text1[0:i] 和 text2[0:j]的最长公共子序列的长度
  12. int[][] dp = new int[m + 1][n + 1];
  13. // 边界情况:
  14. // 当i = 0时,text1[0:i]为空,空字符串和任何字符串的最长公共子序列的长度都是0,
  15. // 因此对任意 0 <= j <= n,有dp[0][j] = 0
  16. dp[0][j] = 0
  17. dp[i][0] = 0;
  18. for (int i = 1; i <= m; i++) {
  19. char c1 = text1.charAt(i - 1);
  20. for (int j = 1; j <= n; j++) {
  21. char c2 = text2.charAt(j - 1);
  22. if (c1 == c2) {
  23. // 当text1[0:i-1] = text2[0:j-1]的最长公共子序列再增加一个字符(即公共字符)即可得到text1[0:i]和text2[0:j]的最长公共子序列
  24. dp[i][j] = dp[i - 1][j - 1] + 1;
  25. } else {
  26. dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
  27. }
  28. }
  29. }
  30. return dp[m][n];
  31. }
  32. }
  33. // 时间复杂度:O(mn),其中m和n分别是字符串text1和text2的长度。二维数组dp有m+1行和n+1列,需要对dp中的每个元素进行计算
  34. // 空间复杂度:O(mn),其中m和n分别是字符串text1和text2的长度。创建了m+1行n+1列的二维数组 dp
  35. class Solution {
  36. public int longestCommonSubsequence(String text1, String text2) {
  37. int m = text1.length();
  38. int n = text2.length();
  39. // 第一步:状态定义dp[i][j]:长度为[0, i-1]的字符串text1 与 长度为[0, j-1]的字符串text2的最长公共子序列
  40. int[][] dp = new int[m+1][n+1];
  41. // 第二步:初始化:text1[0, i-1]和空串的最长公共子序列自然是0,所以dp[i][0] = 0。同理dp[0][j]也是0
  42. // 第四步:确定遍历顺序
  43. for(int i = 1; i <= m; i++){
  44. char char1 = text1.charAt(i-1);
  45. for(int j = 1; j <= n; j++){
  46. char char2 = text2.charAt(j-1);
  47. // 第三步:状态转移方程
  48. if(char1 == char2){
  49. // 如果text1[i-1] 与 text2[j-1]相同,那么找到了一个公共元素,所以dp[i][j] = dp[i-1][j-1] + 1
  50. dp[i][j] = dp[i-1][j-1] + 1;
  51. }else {
  52. // 如果text1[i-1] 与 text2[j-1]不相同,那就看看text1[0, i-2] 与 text2[0, j-1]的最长公共子序列 和 text1[0, i-1]与text2[0, j-2]的最长公共子序列,取最大的
  53. dp[i][j] =Math.max(dp[i-1][j], dp[i][j-1]);
  54. }
  55. }
  56. }
  57. // 第五步:确定最大值
  58. return dp[m][n];
  59. }
  60. }

11111 - 验证回文串(125)- 26

  1. // 如果在将所有大写字符转换为小写字符、并移除所有非字母数字字符之后,短语正着读和反着读都一样。则可以认为该短语是一个 回文串
  2. // 给你一个字符串 s,如果它是 回文串 ,返回 true ;否则,返回 false
  3. // 输入: s = "A man, a plan, a canal: Panama"
  4. // 输出:true
  5. // 解释:"amanaplanacanalpanama" 是回文串
  6. // https://leetcode.cn/problems/valid-palindrome/
  7. class Solution {
  8. public boolean isPalindrome(String s) {
  9. char[] c = s.toLowerCase().toCharArray();
  10. int i = 0, j = c.length - 1;
  11. while(i < j){
  12. while(!isValid(c[i]) && i < j){
  13. i++;
  14. }
  15. while(!isValid(c[j]) && i < j){
  16. j--;
  17. }
  18. if(c[i] != c[j]){
  19. return false;
  20. }
  21. i++;
  22. j--;
  23. }
  24. return true;
  25. }
  26. private boolean isValid(char c){
  27. return (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9');
  28. }
  29. }

11111 - 验证回文串II(680)- 11

  1. // https://leetcode.cn/problems/valid-palindrome-ii/description/
  2. // 给你一个字符串s,最多可以从中删除一个字符
  3. // 请你判断 s 是否能成为回文字符串:如果能,返回true ;否则,返回false
  4. // 输入:s = "aba"
  5. // 输出:true
  6. // 输入:s = "abc"
  7. // 输出:false
  8. class Solution {
  9. public boolean validPalindrome(String s) {
  10. // 双指针
  11. int left = 0;
  12. int right = s.length()-1;
  13. while(left < right){
  14. int leftValue = s.charAt(left);
  15. int rightValue = s.charAt(right);
  16. // 若首尾字符相同,则移动前后指针
  17. if(leftValue == rightValue){
  18. left++;
  19. right--;
  20. }else{
  21. // 若首尾字符不同,则判断(首+1 与 尾)或者(首 与 尾+1)
  22. return valid(s, left + 1, right) || valid(s, left, right - 1);
  23. }
  24. }
  25. return true;
  26. }
  27. // 此方法判断回文字符串,完全匹配
  28. public boolean valid(String s, int left, int right){
  29. for(int i = left, j = right; i < j; i++, j--){
  30. int a = s.charAt(i);
  31. int b = s.charAt(j);
  32. if(a != b) return false;
  33. }
  34. return true;
  35. }
  36. }

22222 - 最长公共子串

https://blog.csdn.net/ly0724ok/article/details/119876759

22222 - 最小覆盖子串(76)- 77

  1. // https://leetcode.cn/problems/minimum-window-substring/
  2. // 给你一个字符串 s 、一个字符串 t 。返回 s 中涵盖 t 所有字符的最小子串。如果 s 中不存在涵盖 t 所有字符的子串,则返回空字符串 ""
  3. // 困难:https://leetcode.cn/problems/minimum-window-substring/
  4. // 输入:s = "ADOBECODEBANC", t = "ABC"
  5. // 输出:"BANC"
  6. class Solution {
  7. public String minWindow(String s, String t) {
  8. // 1.维护两个map记录窗口中的符合条件的字符以及need的字符
  9. Map<Character, Integer> window = new HashMap<>();
  10. // need中存储的是需要的字符以及需要的对应的数量
  11. Map<Character, Integer> need = new HashMap<>();
  12. for(char c : t.toCharArray()){
  13. need.put(c, need.getOrDefault(c, 0) + 1);
  14. }
  15. int left = 0, right = 0; //双指针
  16. int count = 0; // count记录当前窗口中符合need要求的字符的数量,当count == need.size()时即可shrik窗口
  17. int start = 0; // start表示符合最优解的substring的起始位序
  18. int len = Integer.MAX_VALUE; // len用来记录最终窗口的长度,并且以len作比较,淘汰选出最小的substring的len
  19. // 一次遍历找“可行解”
  20. while(right < s.length()){
  21. // 更新窗口
  22. char c = s.charAt(right);
  23. right++; // 窗口扩大
  24. // window.put(c,window.getOrDefault(c,0)+1);其实并不需要将s中所有的都加入windowsmap,只需要将need中的加入即可
  25. if(need.containsKey(c)){
  26. window.put(c, window.getOrDefault(c, 0) + 1);
  27. if(need.get(c).equals(window.get(c))){
  28. count++;
  29. }
  30. }
  31. // System.out.println****Debug位置
  32. // shrink左边界,找符合条件的最优解
  33. while(count == need.size()){
  34. // 不断“打擂”找满足条件的len最短值, 并记录最短的子串的起始位序start
  35. if(right - left < len){
  36. len = right - left;
  37. start = left;
  38. }
  39. // 更新窗口——这段代码逻辑几乎完全同上面的更新窗口
  40. char d = s.charAt(left);
  41. left++; //窗口缩小
  42. if(need.containsKey(d)){
  43. //window.put(d,window.get(d)-1);——bug:若一进去就将window对应的键值缩小,就永远不会满足下面的if,while也会一直执行,知道left越界,因此,尽管和上面对窗口的处理几乎一样,但是这个处理的顺序还是很关键的!要细心!
  44. if(need.get(d).equals(window.get(d))){
  45. count--;
  46. }
  47. window.put(d,window.get(d)-1);
  48. }
  49. }
  50. }
  51. return len == Integer.MAX_VALUE ? "" : s.substring(start,start+len);
  52. }
  53. }

给一个字符串,输出这个字符串的一个最短子串,这个子串重复拼接能形成整个字符串

  1. (如字符串ababab,求得子串ab)若无这种子串,则输出整个字符串;写完有bug没调出来,就问整体思路,说思路是对的但细节有点问题
  2. https://blog.csdn.net/taozhi867243023/article/details/124048733

反转字符串中的单词III(557)- 17

  1. // https://leetcode.cn/problems/reverse-words-in-a-string-iii/
  2. // 给定一个字符串 s ,你需要反转字符串中每个单词的字符顺序,同时仍保留空格和单词的初始顺序
  3. // 输入:s = "Let's take LeetCode contest"
  4. // 输出:"s'teL ekat edoCteeL tsetnoc"
  5. // s 不包含任何开头或结尾空格
  6. // s 中的所有单词都用一个空格隔开
  7. class Solution {
  8. public String reverseWords(String s) {
  9. String[] split = s.split(" ");
  10. for (int i = 0; i < split.length; i++) {
  11. split[i] = new StringBuffer(split[i]).reverse().toString();
  12. }
  13. return String.join(" ", split);
  14. }
  15. public String reverseWords1(String s) {
  16. StringBuffer ret = new StringBuffer();
  17. int length = s.length();
  18. int i = 0;
  19. while (i < length) {
  20. int start = i;
  21. while (i < length && s.charAt(i) != ' ') {
  22. i++;
  23. }
  24. for (int p = start; p < i; p++) {
  25. ret.append(s.charAt(start + i - 1 - p));
  26. }
  27. while (i < length && s.charAt(i) == ' ') {
  28. i++;
  29. ret.append(' ');
  30. }
  31. }
  32. return ret.toString();
  33. }
  34. }

最长连续递增序列(674)- 11

  1. // https://leetcode.cn/problems/longest-continuous-increasing-subsequence/
  2. // 给定一个未经排序的整数数组,找到最长且 连续递增的子序列,并返回该序列的长度
  3. // 连续递增的子序列 可以由两个下标 l 和 r(l < r)确定,如果对于每个 l <= i < r,都有 nums[i] < nums[i + 1] ,那么子序列 [nums[l], nums[l + 1], ..., nums[r - 1], nums[r]] 就是连续递增子序列
  4. // 输入:nums = [1,3,5,4,7]
  5. // 输出:3
  6. // 解释:最长连续递增序列是 [1,3,5], 长度为3
  7. // 尽管 [1,3,5,7] 也是升序的子序列, 但它不是连续的,因为 5 和 7 在原数组里被 4 隔开
  8. class Solution {
  9. public int findLengthOfLCIS(int[] nums) {
  10. int maxlength = 1;
  11. int premax = 1;
  12. for(int i = 0; i < nums.length - 1; i++){
  13. if(nums[i+1] > nums[i]) premax++;
  14. else premax = 1;
  15. maxlength = Math.max(maxlength, premax);
  16. }
  17. return maxlength;
  18. }
  19. public int findLengthOfLCIS1(int[] nums) {
  20. int ans = 0;
  21. int n = nums.length;
  22. int start = 0;
  23. for (int i = 0; i < n; i++) {
  24. if (i > 0 && nums[i] <= nums[i - 1]) {
  25. start = i;
  26. }
  27. ans = Math.max(ans, i - start + 1);
  28. }
  29. return ans;
  30. }
  31. }

字符串中找出连续最长的数字串

  1. // https://blog.csdn.net/ren__wei_/article/details/116030619
  2. // 读入一个字符串str,输出字符串str中的连续最长的数字串
  3. // 给一个输入abc123nj5nk88990wze这里面最长的数字串是88990,并将其输出
  4. public class Main{
  5. public static void main(String[] args){
  6. Scanner sc = new Scanner(System.in);
  7. String str = sc.nextLine();
  8. String cur = "";
  9. String result = "";
  10. for(int i = 0; i < str.length(); i++){
  11. char ch = str.charAt(i);
  12. // 当前字符是数字的话,就把这个字符放进cur中,加""的原因是变成字符串
  13. if(ch >= '0' && ch <= '9'){
  14. cur = cur + ch + "";
  15. }else{
  16. if(cur.length() > result.length()){
  17. result = cur;
  18. }else{
  19. cur = "";
  20. }
  21. }
  22. }
  23. // 循环结束后,再次进行判断,防止输入的字符串全是数字
  24. if(cur.length() > result.length()){
  25. result = cur;
  26. }
  27. System.out.println(result);
  28. }
  29. }

22222 - 根据字符出现频率排序(451)- 6

  1. // https://leetcode.cn/problems/sort-characters-by-frequency/
  2. // 给定一个字符串 s ,根据字符出现的 频率 对其进行 降序排序 。一个字符出现的 频率 是它出现在字符串中的次数
  3. // 返回 已排序的字符串 。如果有多个答案,返回其中任何一个
  4. // 输入: s = "Aabb"
  5. // 输出: "bbAa"
  6. // 解释: 此外,"bbaA"也是一个有效的答案,但"Aabb"是不正确的
  7. // 注意'A'和'a'被认为是两种不同的字符
  8. class Solution {
  9. public String frequencySort(String s) {
  10. Map<Character, Integer> map = new HashMap<Character, Integer>();
  11. int maxFreq = 0;
  12. int length = s.length();
  13. for (int i = 0; i < length; i++) {
  14. char c = s.charAt(i);
  15. int frequency = map.getOrDefault(c, 0) + 1;
  16. map.put(c, frequency);
  17. maxFreq = Math.max(maxFreq, frequency);
  18. }
  19. StringBuffer[] buckets = new StringBuffer[maxFreq + 1];
  20. for (int i = 0; i <= maxFreq; i++) {
  21. buckets[i] = new StringBuffer();
  22. }
  23. for (Map.Entry<Character, Integer> entry : map.entrySet()) {
  24. char c = entry.getKey();
  25. int frequency = entry.getValue();
  26. buckets[frequency].append(c);
  27. }
  28. StringBuffer sb = new StringBuffer();
  29. for (int i = maxFreq; i > 0; i--) {
  30. StringBuffer bucket = buckets[i];
  31. int size = bucket.length();
  32. for (int j = 0; j < size; j++) {
  33. for (int k = 0; k < i; k++) {
  34. sb.append(bucket.charAt(j));
  35. }
  36. }
  37. }
  38. return sb.toString();
  39. }
  40. }
  41. // 时间复杂度:O(n + k)
  42. // 空间复杂度:O(n + k)
  1. 求一个字符串中的出现最大次数的字符并返回该次数
  2. 驼峰子串的去除,如字符串AaADdDEeEbcvQv,AaA、DdD、EeE和vQv均为驼峰,需要去除,输出结果bc,使用栈进行一次遍历即可
  3. 给一个String字符串abcabcdabddd……………iii…….iii,然后给abc iii abcd ab,根据下面的去切分上面的字符串,输出结果abc|abcd|ab|iii|iii
  4. 代码题:一串字符串,判断第一个不重复的单词
  5. 编程:完整的括号,能否完全配对
  6. 检查字符串是否满足ipv4的要求

数组

11111 - 非重复数字的全排列(46)- 181

  1. // https://leetcode.cn/problems/permutations/
  2. // 给定一个不含重复数字的数组 nums ,返回其 所有可能的全排列 。你可以 按任意顺序 返回答案
  3. // 输入:nums = [1,2,3]
  4. // 输出:[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
  5. class Solution {
  6. List<List<Integer>> result = new ArrayList<List<Integer>>();
  7. List<Integer> path = new ArrayList<Integer>();
  8. public List<List<Integer>> permute(int[] nums) {
  9. process(nums);
  10. return result;
  11. }
  12. public void process(int[] nums){
  13. // 此处不要加终止条件,根据纵向递归判断终止条件
  14. if(path.size() == nums.length){
  15. result.add(new ArrayList<>(path));
  16. }
  17. // 纵向递归:有终止条件
  18. for(int i = 0; i < nums.length; i++){
  19. // path中已存在,则跳过
  20. if(path.contains(nums[i])) continue;
  21. path.add(nums[i]);
  22. process(nums);
  23. path.remove(path.size()-1);
  24. }
  25. }
  26. }

22222 - 删除有序数组中的重复项(26)- 33

  1. // https://leetcode.cn/problems/remove-duplicates-from-sorted-array/
  2. // 给你一个 升序排列 的数组 nums ,请你 原地 删除重复出现的元素,使每个元素 只出现一次 ,返回删除后数组的新长度。元素的 相对顺序 应该保持 一致
  3. // 由于在某些语言中不能改变数组的长度,所以必须将结果放在数组nums的第一部分。更规范地说,如果在删除重复项之后有 k 个元素,那么 nums 的前 k 个元素应该保存最终结果
  4. // 将最终结果插入 nums 的前 k 个位置后返回 k
  5. // 不要使用额外的空间,你必须在 原地 修改输入数组 并在使用 O(1) 额外空间的条件下完成
  6. // 判题标准:
  7. // 系统会用下面的代码来测试你的题解:
  8. // int[] nums = [...]; // 输入数组
  9. // int[] expectedNums = [...]; // 长度正确的期望答案
  10. // int k = removeDuplicates(nums); // 调用
  11. // assert k == expectedNums.length;
  12. // for (int i = 0; i < k; i++) {
  13. // assert nums[i] == expectedNums[i];
  14. // }
  15. // 如果所有断言都通过,那么您的题解将被 通过
  16. class Solution {
  17. public int removeDuplicates(int[] nums) {
  18. if(nums == null || nums.length == 0) return 0;
  19. int slow = 0;
  20. int fast = 1;
  21. while(fast < nums.length){
  22. // 若慢指针指向的元素 与 快指针指向的元素不相等,表示慢指针指向元素不是重置项
  23. if(nums[slow] != nums[fast]){
  24. // 向后慢指针,并将快指针元素 赋值给 慢指针后一位元素,进入下一次循环判断
  25. slow++;
  26. nums[slow] = nums[fast];
  27. }
  28. // 每判断一次都向后移动快指针
  29. fast++;
  30. }
  31. return slow + 1;
  32. }
  33. }
  34. // 时间复杂度:O(n)。 空间复杂度:O(1)

11111 - 多数元素(169)- 60

  1. // https://leetcode.cn/problems/majority-element/
  2. class Solution {
  3. public int majorityElement(int[] nums) {
  4. Map<Integer, Integer> map = new HashMap<>();
  5. for (int num : nums) {
  6. if(map.containsKey(num)){
  7. map.put(num, map.get(num) + 1);
  8. }else {
  9. map.put(num, 1);
  10. }
  11. }
  12. Integer s = map.values().stream().max(Integer::compareTo).orElse(1);
  13. System.out.println(s);
  14. for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
  15. if(entry.getValue().equals(s)){
  16. return entry.getKey();
  17. }
  18. }
  19. return -1;
  20. }
  21. public int majorityElement1(int[] nums) {
  22. int cand_num = nums[0];
  23. int count = 1;
  24. for (int i = 1; i < nums.length; ++i) {
  25. if (cand_num == nums[i])
  26. ++count;
  27. else if (--count == 0) {
  28. cand_num = nums[i];
  29. count = 1;
  30. }
  31. }
  32. return cand_num;
  33. }
  34. public int majorityElement2(int[] nums) {
  35. Arrays.sort(nums);
  36. return nums[nums.length / 2];
  37. }
  38. }

最大数(179)- 48

  1. // https://leetcode.cn/problems/largest-number/
  2. // 给定一组非负整数 nums,重新排列每个数的顺序(每个数不可拆分)使之组成一个最大的整数
  3. // 输入:nums = [3,30,34,5,9]
  4. // 输出:"9534330"
  5. class Solution {
  6. public String largestNumber(int[] nums) {
  7. int n = nums.length;
  8. String[] numsToWord = new String[n];
  9. for(int i = 0; i < n; i++){
  10. numsToWord[i] = String.valueOf(nums[i]);
  11. }
  12. // compareTo()方法比较的时候是按照ASCII码逐位比较的
  13. // 通过比较(a+b)和(b+a)的大小,就可以判断出a,b两个字符串谁应该在前面
  14. // 所以[3,30,34]排序后变为[34,3,30]
  15. // [233,23333]排序后变为[23333,233]
  16. Arrays.sort(numsToWord, (a, b)->{
  17. return (b + a).compareTo(a + b);
  18. });
  19. // 如果排序后的第一个元素是0,那后面的元素肯定小于或等于0,则可直接返回0
  20. if(numsToWord[0].equals("0")){
  21. return "0";
  22. }
  23. StringBuilder sb = new StringBuilder();
  24. for(int i = 0; i < n; i++){
  25. sb.append(numsToWord[i]);
  26. }
  27. return sb.toString();
  28. }
  29. }

把数组排成最小的数(面试题45)- 17

  1. // https://leetcode.cn/problems/ba-shu-zu-pai-cheng-zui-xiao-de-shu-lcof/
  2. // 输入一个非负整数数组,把数组里所有数字拼接起来排成一个数,打印能拼接出的所有数字中最小的一个
  3. // 输入: [3,30,34,5,9]
  4. // 输出: "3033459"
  5. class Solution {
  6. public String minNumber(int[] nums) {
  7. String[] strs = new String[nums.length];
  8. for (int i = 0; i < nums.length; i++) {
  9. strs[i] = String.valueOf(nums[i]);
  10. }
  11. Arrays.sort(strs, (o1, o2) -> (o1 + o2).compareTo(o2 + o1));
  12. StringBuilder sb = new StringBuilder();
  13. for (String str : strs) {
  14. sb.append(str);
  15. }
  16. return sb.toString();
  17. }
  18. }

1 - 合并两个有序数组(88)- 185

  1. // https://leetcode.cn/problems/merge-sorted-array/description/
  2. // 给你两个按 非递减顺序 排列的整数数组 nums1 和 nums2,另有两个整数 m 和 n ,分别表示 nums1 和 nums2 中的元素数目。
  3. // 请你 合并 nums2 到 nums1 中,使合并后的数组同样按 非递减顺序 排列。
  4. // 注意:最终,合并后数组不应由函数返回,而是存储在数组 nums1 中。为了应对这种情况,nums1 的初始长度为 m + n,其中前 m 个元素表示应合并的元素,后 n 个元素为 0 ,应忽略。nums2 的长度为 n
  5. // 输入:nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3
  6. // 输出:[1,2,2,3,5,6]
  7. // 解释:需要合并 [1,2,3] 和 [2,5,6] 。
  8. // 合并结果是 [1,2,2,3,5,6] ,其中斜体加粗标注的为 nums1 中的元素
  9. class Solution {
  10. public void merge(int[] nums1, int m, int[] nums2, int n) {
  11. int[] sorted = new int[m + n];
  12. // 双指针,p1指向nums1数组,p2指向nums2数组
  13. int p1 = 0, p2 = 0;
  14. // cur表示当前指针对应的元素值
  15. int cur;
  16. while (p1 < m || p2 < n) {
  17. if (p1 == m) {
  18. // nums1数组已经取完,此时完全取nums2数组的值即可
  19. cur = nums2[p2++];
  20. } else if (p2 == n) {
  21. // nums2数组已经取完,此时完全取nums1数组的值即可
  22. cur = nums1[p1++];
  23. } else if (nums1[p1] < nums2[p2]) {
  24. cur = nums1[p1++];
  25. } else {
  26. cur = nums2[p2++];
  27. }
  28. // 由于上述步骤已经将p1或p2完成的+1,所以此处的下标要-1
  29. sorted[p1 + p2 - 1] = cur;
  30. }
  31. for (int i = 0; i < m + n; i++) {
  32. nums1[i] = sorted[i];
  33. }
  34. }
  35. }

0 - 三数之和(15)- 267

  1. // https://leetcode.cn/problems/3sum/
  2. // 给你一个整数数组nums,判断是否存在三元组[nums[i],nums[j],nums[k]],满足i != j、i != k且j != k,
  3. // 同时还满足nums[i] + nums[j] + nums[k] == 0。请你返回所有和为0且不重复的三元组
  4. // 注意:答案中不可以包含重复的三元组
  5. // 输入:nums = [-1,0,1,2,-1,-4]
  6. // 输出:[[-1,-1,2],[-1,0,1]]
  7. // 解释:
  8. // nums[0] + nums[1] + nums[2] = (-1) + 0 + 1 = 0 。
  9. // nums[1] + nums[2] + nums[4] = 0 + 1 + (-1) = 0 。
  10. // nums[0] + nums[3] + nums[4] = (-1) + 2 + (-1) = 0 。
  11. // 不同的三元组是 [-1,0,1] 和 [-1,-1,2] 。
  12. // 注意,输出的顺序和三元组的顺序并不重要
  13. class Solution {
  14. // 定义三个指针,保证遍历数组中的每一个结果
  15. // 画图,解答
  16. public List<List<Integer>> threeSum(int[] nums) {
  17. // 定义一个结果集
  18. List<List<Integer>> res = new ArrayList<>();
  19. // 数组的长度
  20. int len = nums.length;
  21. // 当前数组的长度为空,或者长度小于3时,直接退出
  22. if(nums == null || len < 3){
  23. return res;
  24. }
  25. // 将数组进行排序
  26. Arrays.sort(nums);
  27. // 遍历数组中的每一个元素
  28. for(int i = 0; i<len;i++){
  29. // 如果遍历的起始元素大于0,就直接退出
  30. // 原因,此时数组为有序的数组,最小的数都大于0了,三数之和肯定大于0
  31. if(nums[i]>0){
  32. break;
  33. }
  34. // 去重,当起始的值等于前一个元素,那么得到的结果将会和前一次相同
  35. if(i > 0 && nums[i] == nums[i-1]) continue;
  36. int l = i +1;
  37. int r = len-1;
  38. // 当 l 不等于 r时就继续遍历
  39. while(l < r){
  40. // 将三数进行相加
  41. int sum = nums[i] + nums[l] + nums[r];
  42. // 如果等于0,将结果对应的索引位置的值加入结果集中
  43. if(sum==0){
  44. // 将三数的结果集加入到结果集中
  45. res.add(Arrays.asList(nums[i], nums[l], nums[r]));
  46. // 在将左指针和右指针移动的时候,先对左右指针的值,进行判断
  47. // 如果重复,直接跳过。
  48. // 去重,因为 i 不变,当此时 l取的数的值与前一个数相同,所以不用在计算,直接跳
  49. while(l < r && nums[l] == nums[l+1]) {
  50. l++;
  51. }
  52. // 去重,因为 i不变,当此时 r 取的数的值与前一个相同,所以不用在计算
  53. while(l< r && nums[r] == nums[r-1]){
  54. r--;
  55. }
  56. // 将 左指针右移,将右指针左移。
  57. l++;
  58. r--;
  59. // 如果结果小于0,将左指针右移
  60. }else if(sum < 0){
  61. l++;
  62. // 如果结果大于0,将右指针左移
  63. }else if(sum > 0){
  64. r--;
  65. }
  66. }
  67. }
  68. return res;
  69. }
  70. }

最长公共前缀(14)- 56

  1. // https://leetcode.cn/problems/longest-common-prefix/
  2. // 编写一个函数来查找字符串数组中的最长公共前缀。
  3. // 输入:strs = ["flower","flow","flight"]
  4. // 输出:"fl"
  5. class Solution {
  6. public String longestCommonPrefix(String[] strs) {
  7. String shortest = strs[0];
  8. for (String str : strs) {
  9. if (str.length() < shortest.length()) {
  10. shortest = str;
  11. }
  12. }
  13. String res = shortest;
  14. for (int i = 0; i < shortest.length(); i++) {
  15. for (String str : strs) {
  16. if (!str.startsWith(res)) {
  17. res = res.substring(0, res.length() - 1);
  18. }
  19. }
  20. }
  21. return res;
  22. }
  23. }

最大子数组和(53)- 236

  1. // https://leetcode.cn/problems/maximum-subarray/
  2. // 给你一个整数数组 nums ,请你找出一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。
  3. // 子数组 是数组中的一个连续部分
  4. // 输入:nums = [-2,1,-3,4,-1,2,1,-5,4]
  5. // 输出:6
  6. // 解释:连续子数组 [4,-1,2,1] 的和最大,为 6
  7. class Solution {
  8. public int maxSubArray(int[] nums) {
  9. int len = nums.length;
  10. // 第一步:定义状态:dp[i]表示第i个元素为尾结点构成的子数组的和
  11. int[] dp = new int[len];
  12. // 第二步:初始化
  13. dp[0] = nums[0];
  14. int maxSum = dp[0];
  15. // 第四步:确定遍历顺序
  16. for(int i = 1; i < len; i++){
  17. // 第三步:状态转移
  18. // dp[i-1] > 0,则dp[i] = dp[i-1] + nums[i]。此处不能判断dp[i-1] + nums[i] > 0,需考虑dp[i-1]为负数场景
  19. // dp[i-1] <= 0,则dp[i] = nums[i];
  20. if(dp[i-1] > 0){
  21. dp[i] = dp[i-1] + nums[i];
  22. }else {
  23. dp[i] = nums[i];
  24. }
  25. maxSum = Math.max(maxSum, dp[i]);
  26. }
  27. // 第五步:确定最大值
  28. return maxSum;
  29. }
  30. public int maxSubArray1(int[] nums) {
  31. int ans = nums[0]; // 最终求出的连续子数组的最大和
  32. int sum = 0; // 当前元素前面的连续子数组的最大和
  33. for(int num: nums) {
  34. if(sum > 0) {
  35. sum += num; // 说明sum对结果有增益效果,则sum保留并加上当前遍历数字
  36. } else {
  37. sum = num; // 说明sum对结果无增益效果,需要舍弃,则sum直接更新为当前遍历数字
  38. }
  39. ans = Math.max(ans, sum);
  40. }
  41. return ans;
  42. }
  43. }

0 - 最长重复子数组(718) - 58

  1. // https://leetcode.cn/problems/maximum-length-of-repeated-subarray/
  2. // 给两个整数数组 nums1 和 nums2 ,返回 两个数组中 公共的 、长度最长的子数组的长度 。
  3. // 输入:nums1 = [1,2,3,2,1], nums2 = [3,2,1,4,7]
  4. // 输出:3
  5. // 解释:长度最长的公共子数组是 [3,2,1]
  6. class Solution {
  7. public int findLength(int[] A, int[] B) {
  8. int m = A.length;
  9. int n = B.length;
  10. int maxLength = 0;
  11. // 第一步:定义状态:dp[i][j]表示A[i-1],B[j-1]重复子数组
  12. int[][] dp = new int[m+1][n+1];
  13. // 第二步:初始化
  14. // Arrays.fill(dp, 0);
  15. // 第四步:确认遍历顺序
  16. for(int i = 1; i <= m; i++){
  17. for(int j = 1; j <= n; j++){
  18. // 第三步:状态转移
  19. // A[i-1] = B[j-1],dp[i][j] = dp[i-1][j-1] + 1
  20. // A[i-1] != B[j-1],dp[i][j] = 0
  21. if(A[i-1] == B[j-1]){
  22. dp[i][j] = dp[i-1][j-1] + 1;
  23. }
  24. maxLength = Math.max(maxLength, dp[i][j]);
  25. }
  26. }
  27. // 第五步:确认最大值
  28. return maxLength;
  29. }
  30. public int findLength1(int[] A, int[] B) {
  31. int m = A.length;
  32. int n = B.length;
  33. int[] dp = new int[n+1];
  34. int ans = 0;
  35. for(int i = m-1; i >= 0; i--){
  36. int p = 0;
  37. int q = 0;
  38. for(int j = n-1; j >= 0; j--){
  39. p = q;
  40. q = dp[j];
  41. dp[j] = (A[i] == B[j]) ? p + 1 : 0;
  42. ans = Math.max(ans,dp[j]);
  43. }
  44. }
  45. return ans;
  46. }
  47. }

1 - 二分查找(704)- 114

  1. // 给定一个n个元素有序的(升序)整型数组nums和一个目标值target,写一个函数搜索nums中的target,
  2. // 如果目标值存在返回下标,否则返回 -1
  3. // https://leetcode.cn/problems/binary-search/
  4. class Solution {
  5. public int search(int[] nums, int target) {
  6. int left = 0, right = nums.length-1;
  7. while(left <= right){
  8. int mid = left + (right - left) / 2;
  9. if(target == nums[mid]){ // 目标值刚好在中间位置
  10. return mid;
  11. }else if(target > nums[mid]) { // 目标值在后半部分
  12. left = mid + 1;
  13. }else{
  14. right = mid - 1; // 目标值在前半部分
  15. }
  16. }
  17. return -1;
  18. }
  19. }
  20. // 时间复杂度:O(log⁡n),其中n是数组的长度
  21. // 空间复杂度:O(1)

22222 - 长度为n的数组乱序存放着0至n-1,现在只能进行0与其他数的交换,完成数组排序

  1. // 问题描述:长度为n的数组乱序存放着0至n-1. 现在只能进行0与其他数的交换,完成数组排序
  2. // 思路:由于乱序数组各元素亮亮不同,且已知数组内容即为0-(n-1),所以只要考虑将0-(n-1)这n个数依次填入数组array即可。
  3. // 一个简单的思路是,由于数组最终内容是array[i]=i,考虑将0与数组第i个位置互换,然后将0与i互换,则i填入位置array[i]

22222 - 小于n的最大数

  1. 6. 给定一个数n,如23121;给定一组数字A如{2,4,9}求由A中元素组成的、小于n的最大数,如小于23121的最大数为22999.
  2. 7. 给一个数组a[],一个数n 232342,求用数组a[]里面数字组合成最大的不大于n的数
  3. // https://blog.csdn.net/weixin_42041027/article/details/125269790

分组的最大数量(2358)

  1. // https://leetcode.cn/problems/maximum-number-of-groups-entering-a-competition/description/
  2. // 给你一个正整数数组 grades ,表示大学中一些学生的成绩。你打算将 所有 学生分为一些 有序 的非空分组,其中分组间的顺序满足以下全部条件:
  3. // 第 i 个分组中的学生总成绩 小于 第 (i + 1) 个分组中的学生总成绩,对所有组均成立(除了最后一组)
  4. // 第 i 个分组中的学生总数 小于 第 (i + 1) 个分组中的学生总数,对所有组均成立(除了最后一组)
  5. // 返回可以形成的 最大 组数
  6. // 输入:grades = [10,6,12,7,3,5]
  7. // 输出:3
  8. // 解释:下面是形成 3 个分组的一种可行方法:
  9. // - 第 1 个分组的学生成绩为 grades = [12] ,总成绩:12 ,学生数:1
  10. // - 第 2 个分组的学生成绩为 grades = [6,7] ,总成绩:6 + 7 = 13 ,学生数:2
  11. // - 第 3 个分组的学生成绩为 grades = [10,3,5] ,总成绩:10 + 3 + 5 = 18 ,学生数:3
  12. // 可以证明无法形成超过 3 个分组

搜索插入位置(35)- 4

  1. // https://leetcode.cn/problems/search-insert-position/
  2. // 给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置
  3. // 请必须使用时间复杂度为 O(log n) 的算法
  4. // 输入: nums = [1,3,5,6], target = 5
  5. // 输出: 2
  6. // 输入: nums = [1,3,5,6], target = 2
  7. // 输出: 1
  8. class Solution {
  9. public int searchInsert(int[] nums, int target) {
  10. int n = nums.length;
  11. int left = 0, right = n - 1, ans = n;
  12. while (left <= right) {
  13. int mid = ((right - left) >> 1) + left;
  14. if (target <= nums[mid]) {
  15. ans = mid;
  16. right = mid - 1;
  17. } else {
  18. left = mid + 1;
  19. }
  20. }
  21. return ans;
  22. }
  23. }

11111 - 合并区间(56)- 106

  1. // https://leetcode.cn/problems/merge-intervals/
  2. // 以数组 intervals 表示若干个区间的集合,其中单个区间为 intervals[i] = [starti, endi] 。请你合并所有重叠的区间,并返回 一个不重叠的区间数组,该数组需恰好覆盖输入中的所有区间
  3. // 输入:intervals = [[1,3],[2,6],[8,10],[15,18]]
  4. // 输出:[[1,6],[8,10],[15,18]]
  5. // 解释:区间 [1,3] 和 [2,6] 重叠, 将它们合并为 [1,6]
  6. class Solution {
  7. public int[][] merge(int[][] intervals) {
  8. List<int[]> result = new ArrayList<>();
  9. // 将数组中的每个子数组按照第一个元素大小进行排序
  10. Arrays.sort(intervals, (o1, o2) -> (o1[0] - o2[0]));
  11. for(int[] interval : intervals){
  12. // 当前集合为空 或者 当前遍历数组的第一个元素 大于 集合中最后一个数组的第二个元素,表明此时数组不需要合并,加上该新数组即可
  13. if(result.size() == 0 || interval[0] > result.get(result.size()-1)[1]){
  14. result.add(interval);
  15. }else{
  16. // 当前遍历数组的第一个元素 不大于 集合中最后一个数组的第二个元素,表明此时两个数组会有重叠,需要合并这两个数组。第二个元素取较大值
  17. result.get(result.size()-1)[1] = Math.max(interval[1], result.get(result.size()-1)[1]);
  18. }
  19. }
  20. // 集合转数组
  21. return result.toArray(new int[result.size()][]);
  22. }
  23. }
  24. // 时间复杂度:O(nlog⁡n)
  25. // 空间复杂度:O(nlog⁡n)

11111 - 组合总和(39)- 62

  1. // https://leetcode.cn/problems/combination-sum/
  2. // 给你一个 无重复元素 的整数数组 candidates 和一个目标整数 target ,找出 candidates 中可以使数字和为目标数 target 的 所有 不同组合 ,并以列表形式返回。你可以按 任意顺序 返回这些组合。
  3. // candidates 中的 同一个 数字可以 无限制重复被选取 。如果至少一个数字的被选数量不同,则两种组合是不同的。
  4. // 对于给定的输入,保证和为 target 的不同组合数少于 150 个。
  5. class Solution {
  6. List<List<Integer>> result = new ArrayList<List<Integer>>();
  7. List<Integer> path = new ArrayList<Integer>();
  8. // 存储计算过程中的值
  9. int sum = 0;
  10. public List<List<Integer>> combinationSum(int[] candidates, int target) {
  11. Arrays.sort(candidates);
  12. backtrack(candidates, target, 0);
  13. return result;
  14. }
  15. public void backtrack(int[] candidates, int target, int start){
  16. if(sum == target){
  17. // 此处不能直接使用path
  18. result.add(new ArrayList<>(path));
  19. return;
  20. }
  21. // 剪枝操作:若sum + candidates[i] > target, 则不进入循环
  22. for(int i = start; i < candidates.length && sum + candidates[i] <= target; i++){
  23. sum = sum + candidates[i];
  24. path.add(candidates[i]);
  25. // 因为candidates中的元素可以无限制重复被选取,所以此处递归传入i,而不是start+1
  26. backtrack(candidates, target, i);
  27. // 去除路径中最后添加的数字
  28. path.remove(path.size() - 1);
  29. // 减去最后添加的数字(此时可能刚好满足条件,或者和超过target)
  30. sum = sum - candidates[i];
  31. }
  32. }
  33. }

11111 - 组合总和II(40)- 35

  1. NC46加起来和为目标值的组合 - 组合总和 II40
  2. // https://www.cnblogs.com/zhengxch/p/15302333.html
  3. // https://leetcode.cn/problems/combination-sum-ii/
  4. // 给定一个候选人编号的集合 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合
  5. // candidates 中的每个数字在每个组合中只能使用 一次
  6. // 注意:解集不能包含重复的组合
  7. // 输入: candidates = [10,1,2,7,6,1,5], target = 8
  8. // 输出:
  9. // [
  10. // [1,1,6],
  11. // [1,2,5],
  12. // [1,7],
  13. // [2,6]
  14. // ]
  15. class Solution {
  16. List<List<Integer>> result = new ArrayList<List<Integer>>();
  17. List<Integer> path = new ArrayList<Integer>();
  18. int sum = 0;
  19. public List<List<Integer>> combinationSum2(int[] candidates, int target) {
  20. Arrays.sort(candidates);
  21. process(candidates, target, 0);
  22. return result;
  23. }
  24. public void process(int[] candidates, int target, int start){
  25. if(sum == target){
  26. result.add(new ArrayList<>(path));
  27. return;
  28. }
  29. for(int i = start; i < candidates.length && sum + candidates[i] <= target; i++){
  30. // 去重,若candidates中存在重复元素,只需要取其中一个元素进行递归操作即可
  31. // 后续相同的元素就不需要再进行求和操作,因为肯定与前一个相同元素求出的结果一致,此时就重复了
  32. if(i > start && candidates[i] == candidates[i-1]) continue;
  33. sum = sum + candidates[i];
  34. path.add(candidates[i]);
  35. process(candidates, target, i + 1);
  36. // 回溯
  37. path.remove(path.size() - 1);
  38. sum = sum - candidates[i];
  39. }
  40. }
  41. }
  1. 给定一个二维数组,数值表示高度,球只能往低处或者数值相等处走,给定球的初始位置,判断球是否能到达边界?
  2. 给定一个数组,让数组中的奇数在前,偶数在后,奇数正序,偶数逆序
  3. 找出数组中第二大的数,不能排序,不能用库
  4. 一个山峰型数组(先单调增后单调减),对数组去重排序并输出,比如输入[1,3,5,6,4,3,2,1],去重并排序后输出[1,2,3,4,5,6],要求时间复杂度O(n),空间复杂度O(1),我的解法是先找到最大值对应下标,从而把数组分成前半段与后半段,然后从右向左的顺序取后半部分数组每个数字,并将其依次插入到前半部分,遇到重复则丢弃
  5. 编程实现两个数组相乘,输出一个数组
  6. 牛牛有n堆石子堆。 牛牛可以对任意一堆石子数量大于1的石子堆进行分裂操作,分裂成两堆新的石子数量都大于等于1的石子堆。 现在牛牛需要通过分裂得到m堆石子,他想知道这m堆石子的最小值最大可以是多少?
    6 8 17
    3 3 4 4 17。。。 3
    4 4 6 8 9。。。 4
    5 5 6 7 8 。。。5

二叉树

二叉树的中序遍历(94)- 5

  1. class Solution {
  2. public List<Integer> inorderTraversal(TreeNode root) {
  3. List<Integer> res = new ArrayList<Integer>();
  4. inorder(root, res);
  5. return res;
  6. }
  7. public void inorder(TreeNode root, List<Integer> res) {
  8. if (root == null) {
  9. return;
  10. }
  11. inorder(root.left, res);
  12. res.add(root.val);
  13. inorder(root.right, res);
  14. }
  15. }

二叉树中序非递归

  1. public class Solution {
  2. public List<Integer> inorderTraversal(TreeNode root) {
  3. // 栈 先进后出
  4. // 前序遍历,出栈顺序:根左右; 入栈顺序:右左根
  5. // 中序遍历,出栈顺序:左根右; 入栈顺序:右根左
  6. // 后序遍历,出栈顺序:左右根; 入栈顺序:根右左
  7. List<Integer> ans = new ArrayList<Integer>();
  8. Stack<TreeNode> stack = new Stack<>();
  9. // root为空且stack为空,遍历结束
  10. while (root != null || !stack.isEmpty()) {
  11. // 先根节点、然后左子树入栈
  12. while (root != null) {
  13. stack.push(root);
  14. root = root.left;
  15. }
  16. // 此时root==null,说明上一步的root没有左子树
  17. // 1. 执行左出栈。因为此时root==null,导致root.right一定为null
  18. // 2. 执行下一次外层while代码块,根出栈。此时root.right可能存在
  19. // 3a. 若root.right存在,右入栈,再出栈
  20. // 3b. 若root.right不存在,重复步骤2
  21. root = stack.pop();
  22. ans.add(root.val);
  23. root = root.right;
  24. }
  25. return ans;
  26. }
  27. }

平衡二叉树(110)- 4

  1. // 1. 平衡二叉树也叫平衡二叉搜索树(Self-balancing binary search tree)又被称为AVL树,可以保证查询效率较高(是在二叉排序树基础上实现的)
  2. // 2. 具有以下特点:它是一棵空树或它的左右两个子树的高度差的绝对值不超过1,并且左右两个子树都是一棵平衡二叉树。平衡二叉树的常用实现方法有红黑树、AVL、替罪羊树、Treap、伸展树等
  3. // https://leetcode.cn/problems/balanced-binary-tree/description/
  4. class Solution {
  5. boolean ans = true;
  6. public boolean isBalanced(TreeNode root) {
  7. dfs(root);
  8. return ans;
  9. }
  10. private int dfs(TreeNode root){
  11. if(root == null){
  12. return 0;
  13. }
  14. int left = dfs(root.left);
  15. int right = dfs(root.right);
  16. if(Math.abs(left - right) > 1){
  17. ans = false;
  18. }
  19. return Math.max(left, right) + 1;
  20. }
  21. }

字节算法题 - 图1

二叉树的层序遍历(102)- 3

  1. // 给你二叉树的根节点 root ,返回其节点值的 层序遍历 。 (即逐层地,从左到右访问所有节点)。
  2. // https://leetcode.cn/problems/binary-tree-level-order-traversal/
  3. class Solution {
  4. public List<List<Integer>> levelOrder(TreeNode root) {
  5. List<List<Integer>> result = new ArrayList<>();
  6. if(root == null){
  7. return result;
  8. }
  9. Queue<TreeNode> queue = new LinkedList<TreeNode>();
  10. queue.add(root);
  11. while (!queue.isEmpty()){
  12. // 当前层元素集合
  13. List<Integer> level = new ArrayList<>();
  14. // 当前层元素个数
  15. int currentLevelSize = queue.size();
  16. for (int i = 1; i <= currentLevelSize; i++) {
  17. // 从队列中取出当前层元素放入level
  18. TreeNode node = queue.poll();
  19. level.add(node.val);
  20. // 将当前层所有元素的左右子节点放入队列中
  21. if(node.left != null){
  22. queue.add(node.left);
  23. }
  24. if(node.right != null){
  25. queue.add(node.right);
  26. }
  27. }
  28. result.add(level);
  29. }
  30. return result;
  31. }
  32. }

11111 - 二叉树中的最大路径和(124)- 3

  1. // https://leetcode.cn/problems/binary-tree-maximum-path-sum/description/
  2. class Solution {
  3. int maxSum = Integer.MIN_VALUE;
  4. public int maxPathSum(TreeNode root) {
  5. maxGain(root);
  6. return maxSum;
  7. }
  8. public int maxGain(TreeNode node) {
  9. if (node == null) {
  10. return 0;
  11. }
  12. // 递归计算左右子节点的最大贡献值
  13. // 只有在最大贡献值大于 0 时,才会选取对应子节点
  14. int leftGain = Math.max(maxGain(node.left), 0);
  15. int rightGain = Math.max(maxGain(node.right), 0);
  16. // 当前节点的最大路径和取决于该节点的值与该节点的左右子节点的最大贡献值
  17. int priceNewpath = node.val + leftGain + rightGain;
  18. // 更新答案
  19. maxSum = Math.max(maxSum, priceNewpath);
  20. // 返回节点的最大贡献值
  21. return node.val + Math.max(leftGain, rightGain);
  22. }
  23. }

11111 - 对称二叉树(101)- 2

  1. // https://leetcode.cn/problems/symmetric-tree/description/
  2. class Solution {
  3. public boolean isSymmetric(TreeNode root) {
  4. if(root == null) {
  5. return true;
  6. }
  7. // 调用递归函数,比较左节点,右节点
  8. return dfs(root.left, root.right);
  9. }
  10. boolean dfs(TreeNode left, TreeNode right) {
  11. // 递归的终止条件是两个节点都为空
  12. // 或者两个节点中有一个为空
  13. // 或者两个节点的值不相等
  14. if(left == null && right == null) {
  15. return true;
  16. }
  17. if(left == null || right == null) {
  18. return false;
  19. }
  20. if(left.val != right.val) {
  21. return false;
  22. }
  23. // 再递归的比较 左节点的左孩子 和 右节点的右孩子
  24. // 以及比较 左节点的右孩子 和 右节点的左孩子
  25. return dfs(left.left, right.right) && dfs(left.right, right.left);
  26. }
  27. }

二叉树的直径(543)- 2

  1. // https://leetcode.cn/problems/diameter-of-binary-tree/
  2. class Solution {
  3. int ans = 0;
  4. public int diameterOfBinaryTree(TreeNode root) {
  5. ans = 1;
  6. depth(root);
  7. return ans - 1;
  8. }
  9. // 计算该节点的深度
  10. int depth(TreeNode root){
  11. if(root == null){
  12. return 0;
  13. }
  14. int left = depth(root.left); // 左节点为根的子树的深度
  15. int right = depth(root.right); // 右节点为根的子树的深度
  16. // 计算经过该节点的直径
  17. ans = Math.max(ans, left + right + 1);
  18. // 返回该节点为根的子树的深度
  19. return Math.max(left, right) + 1;
  20. }
  21. }
  22. class Solution {
  23. public int diameterOfBinaryTree(TreeNode root) {
  24. return process(root).maxDistance;
  25. }
  26. public static Info process(TreeNode node){
  27. if(node == null){
  28. return new Info(0, 0);
  29. }
  30. // 获取当前节点的左右子树的info信息
  31. Info leftInfo = process(node.left);
  32. Info rightInfo = process(node.right);
  33. // 根据当前节点的左右子树的高度 得到 当前节点的高度
  34. int height = Math.max(leftInfo.height, rightInfo.height) + 1;
  35. // 根据当前节点的左右子树的最大距离 得到 当前节点的距离
  36. int maxDistance = Math.max(Math.max(leftInfo.maxDistance, rightInfo.maxDistance),
  37. leftInfo.height + rightInfo.height);
  38. return new Info(maxDistance, height);
  39. }
  40. }
  41. public class Info{
  42. public int maxDistance;
  43. public int height;
  44. public Info(int dis, int h){
  45. maxDistance = dis;
  46. height = h;
  47. }
  48. }

二叉树的最大深度(543)- 1

  1. // https://leetcode.cn/problems/maximum-depth-of-binary-tree/description/
  2. class Solution {
  3. public int maxDepth(TreeNode root) {
  4. if (root == null){
  5. return 0;
  6. }
  7. int leftDepth = root.left == null ? 0 : maxDepth(root.left);
  8. int rightDepth = root.right == null ? 0 : maxDepth(root.right);
  9. return Math.max(leftDepth, rightDepth) + 1;
  10. }
  11. }

二叉树遍历

整棵二叉树的最大距离

  1. package class008;
  2. // 测试链接:https://leetcode.com/problems/balanced-binary-tree
  3. public class Code08_MaxDistance {
  4. public static class Node {
  5. public int val;
  6. public Node left;
  7. public Node right;
  8. Node(int val) {
  9. this.val = val;
  10. }
  11. }
  12. public static class Info {
  13. public int maxDistance; // 当前节点及其左右子树的最大距离
  14. public int height; // 当前节点及其左右子树的高度
  15. public Info(int dis, int h) {
  16. maxDistance = dis;
  17. height = h;
  18. }
  19. }
  20. public static int maxDistance2(Node head) {
  21. return process(head).maxDistance;
  22. }
  23. public static Info process(Node node) {
  24. if (node == null) {
  25. return new Info(0, 0);
  26. }
  27. // 获取当前节点的左右子树的info信息
  28. Info leftInfo = process(node.left);
  29. Info rightInfo = process(node.right);
  30. // 根据当前节点的左右子树的高度 得到 当前节点的高度
  31. int height = Math.max(leftInfo.height, rightInfo.height) + 1;
  32. // 根据当前节点的左右子树的最大距离 得到 当前节点的距离
  33. int maxDistance = Math.max(Math.max(leftInfo.maxDistance, rightInfo.maxDistance),
  34. leftInfo.height + rightInfo.height + 1);
  35. return new Info(maxDistance, height);
  36. }
  37. }

二叉排序(搜索)树(BST)

对于二叉排序树的任何一个非叶子节点,要求左子节点的值比当前节点的值小右子节点的值比当前节点的值大

顺序存储二叉树

顺序存储二叉树的特点:

  1. 顺序二叉树通常只考虑完全二叉树
  2. 第 n 个元素的左子节点为第 2 * n + 1 个元素
  3. 第 n 个元素的右子节点为第 2 * n + 2 个元素
  4. 第 n 个元素的父节点为第 (n - 1) / 2 个元素
  5. n:表示二叉树中的第几个元素(按0开始编号)

字节算法题 - 图2

二叉树深度优先、广度优先区别

  1. 常见的深度优先搜索(DFS):先序遍历、中序遍历、后序遍历
    1. 深度优先搜索就是沿着每一个分支路径遍历直到不能再深入为止,也就是到达了叶节点。如果到达叶节点,那我们就向上回溯,回到叶节点之前的那一个节点,接着遍历该节点未被访问过的子节点。一直重复这个过程直到所有的节点把遍历完
  2. 常见的广度优先搜索(BFS):层序遍历(按层遍历)

    1. 广度优先搜索就是层序遍历,就是按照树的层次结构一层一层遍历,访问完一层我们就进入下一层,且每个节点只能访问一遍

      队列

      用栈实现队列(232)- 112

      1. // https://leetcode.cn/problems/implement-queue-using-stacks/
      2. class MyQueue {
      3. // 输入栈,用于压入push传入的数据
      4. Stack<Integer> inStack;
      5. // 输出栈,用于pop和peek操作
      6. Stack<Integer> outStack;
      7. public MyQueue() {
      8. inStack = new Stack<>();
      9. outStack = new Stack<>();
      10. }
      11. // 将元素x推到队列的末尾
      12. public void push(int x) {
      13. inStack.push(x);
      14. }
      15. // 从队列的开头移除并返回元素
      16. public int pop() {
      17. if(outStack.isEmpty()){
      18. while(!inStack.isEmpty()){
      19. // 从inStack(先进后出)取出元素,push到outStack(先进后出)。两者刚好使得元素先进先出
      20. outStack.push(inStack.pop());
      21. }
      22. }
      23. return outStack.pop();
      24. }
      25. // 返回队列开头的元素
      26. public int peek() {
      27. if(outStack.isEmpty()){
      28. while(!inStack.isEmpty()){
      29. outStack.push(inStack.pop());
      30. }
      31. }
      32. return outStack.peek();
      33. }
      34. // 如果队列为空,返回true
      35. public boolean empty() {
      36. return outStack.isEmpty() && inStack.isEmpty();
      37. }
      38. }
  3. 两个队列找相同元素;编写测试用例进行测试;优化代码;复杂度;如果是无限队列怎么办

  4. 查找有限队列中重复数据并输出,编写测试用例测试,计算自己代码的时间复杂度,如果是无限队列怎么办。

    链表

    相交链表(160)- 170

    ```java // https://leetcode.cn/problems/intersection-of-two-linked-lists/description/

class Solution {

  1. // 双指针解法
  2. public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
  3. if (headA == null || headB == null) {
  4. return null;
  5. }
  6. ListNode pA = headA, pB = headB;
  7. // 当pA指向末尾时,重新指向headB
  8. // 当pB指向末尾时,重新指向headA,此时能够保证pA与pB最终走的长度是一致相同的
  9. while (pA != pB) {
  10. pA = pA == null ? headB : pA.next;
  11. pB = pB == null ? headA : pB.next;
  12. }
  13. return pA;
  14. }
  15. // 哈希集合
  16. public ListNode getIntersectionNode1(ListNode headA, ListNode headB) {
  17. if(headA == null || headB == null){
  18. return null;
  19. }
  20. ListNode temp1 = headA;
  21. ListNode temp2 = headB;
  22. List<ListNode> listNodes = new ArrayList<>();
  23. while (true){
  24. listNodes.add(temp1);
  25. if(temp1.next == null){
  26. break;
  27. }
  28. temp1 = temp1.next;
  29. }
  30. while (true){
  31. if(listNodes.contains(temp2)){
  32. return temp2;
  33. }else {
  34. if(temp2.next == null){
  35. break;
  36. }
  37. temp2 = temp2.next;
  38. }
  39. }
  40. return null;
  41. }

}

  1. <a name="UaSmH"></a>
  2. ### 反转链表(206)- 532
  3. ```java
  4. // https://leetcode.cn/problems/reverse-linked-list/description/
  5. class Solution {
  6. public ListNode reverseList(ListNode head) {
  7. ListNode prev = null;
  8. ListNode curr = head;
  9. while (curr != null) {
  10. ListNode next = curr.next;
  11. curr.next = prev;
  12. prev = curr;
  13. curr = next;
  14. }
  15. return prev;
  16. }
  17. public ListNode reverseList1(ListNode head) {
  18. // 递归终止条件是当前为空,或者下一个节点为空
  19. if(head==null || head.next==null) {
  20. return head;
  21. }
  22. // 这里的cur就是最后一个节点
  23. ListNode cur = reverseList(head.next);
  24. // 如果链表是 1->2->3->4->5,那么此时的cur就是5
  25. // 而head是4,head的下一个是5,下下一个是空
  26. // 所以head.next.next 就是 5->4
  27. head.next.next = head;
  28. // 防止链表循环,需要将head.next设置为空
  29. head.next = null;
  30. // 每层递归函数都返回cur,也就是最后一个节点
  31. return cur;
  32. }
  33. public ListNode reverseList2(ListNode head) {
  34. if(head == null){
  35. return null;
  36. }
  37. Stack<ListNode> stack = new Stack<>();
  38. ListNode temp = head;
  39. while (true){
  40. stack.push(temp);
  41. if(temp.next == null){
  42. break;
  43. }
  44. temp = temp.next;
  45. }
  46. ListNode listNode = stack.pop();
  47. ListNode listNode1 = listNode;
  48. while (!stack.empty()){
  49. ListNode pop = stack.pop();
  50. pop.next = null;
  51. listNode.next = pop;
  52. listNode = listNode.next;
  53. }
  54. return listNode1;
  55. }
  56. }
  57. class ListNode {
  58. int val;
  59. ListNode next;
  60. ListNode(int val) {
  61. this.val = val;
  62. }
  63. public ListNode(int val, ListNode next) {
  64. this.val = val;
  65. this.next = next;
  66. }
  67. }

22222 - K个一组翻转链表(25)- 286

  1. https://leetcode.cn/problems/reverse-nodes-in-k-group/
  2. 给你链表的头节点 head ,每 k 个节点一组进行翻转,请你返回修改后的链表。
  3. k 是一个正整数,它的值小于或等于链表的长度。如果节点总数不是 k 的整数倍,那么请将最后剩余的节点保持原有顺序。
  4. 你不能只是单纯的改变节点内部的值,而是需要实际进行节点交换
  5. 输入:head = [1,2,3,4,5], k = 2
  6. 输出:[2,1,4,3,5]
  7. /**
  8. * Definition for singly-linked list.
  9. * public class ListNode {
  10. * int val;
  11. * ListNode next;
  12. * ListNode() {}
  13. * ListNode(int val) { this.val = val; }
  14. * ListNode(int val, ListNode next) { this.val = val; this.next = next; }
  15. * }
  16. */
  17. class Solution {
  18. public ListNode reverseKGroup(ListNode head, int k) {
  19. if(head == null || head.next == null) return head;
  20. ListNode tail = head;
  21. for(int i = 0; i < k; i++){
  22. if(tail == null) return head;
  23. tail = tail.next; // 此时tail指向第k个节点的后一节点
  24. }
  25. ListNode newHead = reverse(head, tail);
  26. // 递归翻转从tail为起始节点的k个节点(上一步翻转不包含tail节点),并将返回值链接到head.next
  27. head.next = reverseKGroup(tail, k);
  28. return newHead;
  29. }
  30. // 链表反转,head 至 tailNext上一个节点,左闭右开
  31. private ListNode reverse(ListNode head, ListNode tailNext) {
  32. ListNode pre = null;
  33. ListNode next = null;
  34. while(head != tailNext){
  35. next = head.next;
  36. head.next = pre;
  37. pre = head; // 指针下移
  38. head = next; // 指针下移
  39. }
  40. // 返回最后一个节点,此时head指向最后一个节点的下一节点,即tailNext
  41. return pre;
  42. }
  43. }

字节算法题 - 图3

删除排序链表中的重复元素(83)- 7

  1. // https://leetcode.cn/problems/remove-duplicates-from-sorted-list/description/
  2. class Solution {
  3. public ListNode deleteDuplicates(ListNode head) {
  4. if (head == null) {
  5. return null;
  6. }
  7. ListNode cur = head;
  8. while (cur.next != null) {
  9. if (cur.val == cur.next.val) {
  10. cur.next = cur.next.next;
  11. } else {
  12. cur = cur.next;
  13. }
  14. }
  15. return head;
  16. }
  17. }

判断链表中是否有环(141)- 7

  1. // https://leetcode.cn/problems/linked-list-cycle/description/
  2. class Solution {
  3. public boolean hasCycle(ListNode head) {
  4. if (head == null || head.next == null) {
  5. return false;
  6. }
  7. ListNode slow = head; // 慢指针
  8. ListNode fast = head.next; // 快指针
  9. while (slow != fast) {
  10. if (fast == null || fast.next == null) {
  11. return false;
  12. }
  13. slow = slow.next;
  14. fast = fast.next.next;
  15. }
  16. return true;
  17. }
  18. public boolean hasCycle1(ListNode head) {
  19. if(head == null){
  20. return false;
  21. }
  22. List<ListNode> listNodes = new ArrayList<>();
  23. listNodes.add(head);
  24. ListNode temp = head;
  25. while (true){
  26. if(temp.next == null){
  27. return false;
  28. }
  29. temp = temp.next;
  30. if(listNodes.contains(temp)){
  31. return true;
  32. }
  33. listNodes.add(temp);
  34. }
  35. }
  36. }
  37. class ListNode {
  38. int val;
  39. ListNode next;
  40. ListNode(int val) {
  41. this.val = val;
  42. next = null;
  43. }
  44. }

合并两个有序链表(21)- 4

  1. // https://leetcode.cn/problems/merge-two-sorted-lists/description/
  2. class Solution {
  3. public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
  4. if (l1 == null) return l2;
  5. if (l2 == null) return l1;
  6. ListNode resultNode = new ListNode(0);
  7. ListNode temp = resultNode;
  8. while (l1 != null && l2 != null){
  9. if(l1.val < l2.val){
  10. temp.next = l1;
  11. l1 = l1.next;
  12. }else {
  13. temp.next = l2;
  14. l2 = l2.next;
  15. }
  16. temp = temp.next;
  17. }
  18. if(l1 != null) temp.next = l1;
  19. if(l2 != null) temp.next = l2;
  20. return resultNode.next;
  21. }
  22. public ListNode mergeTwoLists1(ListNode l1, ListNode l2) {
  23. if (l1 == null) {
  24. return l2;
  25. }
  26. else if (l2 == null) {
  27. return l1;
  28. }
  29. else if (l1.val < l2.val) {
  30. l1.next = mergeTwoLists(l1.next, l2);
  31. return l1;
  32. }
  33. else {
  34. l2.next = mergeTwoLists(l1, l2.next);
  35. return l2;
  36. }
  37. }
  38. public ListNode mergeTwoLists2(ListNode list1, ListNode list2) {
  39. if(list1 == null && list2 == null){
  40. return null;
  41. }
  42. if(list1 == null){
  43. return list2;
  44. }
  45. if(list2 == null){
  46. return list1;
  47. }
  48. List<Integer> list = new ArrayList<>();
  49. ListNode temp1 = list1;
  50. ListNode temp2 = list2;
  51. while (true){
  52. if(temp1 == null){
  53. break;
  54. }
  55. list.add(temp1.val);
  56. temp1 = temp1.next;
  57. }
  58. while (true){
  59. if(temp2 == null){
  60. break;
  61. }
  62. list.add(temp2.val);
  63. temp2 = temp2.next;
  64. }
  65. Collections.sort(list);
  66. ListNode root = new ListNode(list.get(0));
  67. ListNode node = root;
  68. for (int i = 1; i < list.size(); i++) {
  69. node.next = new ListNode(list.get(i));
  70. node = node.next;
  71. }
  72. return root;
  73. }
  74. }
  75. class ListNode {
  76. int val;
  77. ListNode next;
  78. ListNode(int val) {
  79. this.val = val;
  80. }
  81. public ListNode(int val, ListNode next) {
  82. this.val = val;
  83. this.next = next;
  84. }
  85. }

环形链表,返回入环的那个节点(142)- 4

  1. // https://leetcode.cn/problems/linked-list-cycle-ii/
  2. public class Solution {
  3. public ListNode detectCycle(ListNode head) {
  4. ListNode temp = head;
  5. Set<ListNode> set = new HashSet<ListNode>();
  6. while (temp != null) {
  7. if (set.contains(temp)) {
  8. return temp;
  9. } else {
  10. set.add(temp);
  11. }
  12. temp = temp.next;
  13. }
  14. return null;
  15. }
  16. public ListNode detectCycle(ListNode head) {
  17. if (head == null) {
  18. return null;
  19. }
  20. ListNode slow = head, fast = head;
  21. while (fast != null) {
  22. slow = slow.next;
  23. if (fast.next != null) {
  24. fast = fast.next.next;
  25. } else {
  26. return null;
  27. }
  28. if (fast == slow) {
  29. fast = head;
  30. while (fast != slow) {
  31. fast = fast.next;
  32. slow = slow.next;
  33. }
  34. return fast;
  35. }
  36. }
  37. return null;
  38. }
  39. }
  40. class ListNode {
  41. int val;
  42. ListNode next;
  43. ListNode(int val) {
  44. this.val = val;
  45. next = null;
  46. }
  47. }

1 - 反转链表 II(92)- 3

  1. // https://leetcode.cn/problems/reverse-linked-list-ii/description/
  2. class Solution {
  3. public ListNode reverseBetween(ListNode head, int left, int right) {
  4. // 重新设置头节点
  5. ListNode dummyNode = new ListNode(-1, head);
  6. ListNode pre = dummyNode;
  7. // pre最终指向left上一个节点
  8. for (int i = 0; i < left - 1; i++) {
  9. pre = pre.next;
  10. }
  11. // cur指向left节点
  12. ListNode cur = pre.next;
  13. ListNode next;
  14. for (int i = 0; i < right - left; i++) {
  15. // 下移指针
  16. next = cur.next;
  17. cur.next = next.next;
  18. next.next = pre.next;
  19. pre.next = next;
  20. }
  21. return dummyNode.next;
  22. }
  23. }

22222 - 链表中倒数第k个节点(剑指 Offer 22)- 2

  1. // https://leetcode.cn/problems/lian-biao-zhong-dao-shu-di-kge-jie-dian-lcof/description/
  2. class Solution {
  3. public ListNode getKthFromEnd(ListNode head, int k) {
  4. ListNode first = head;
  5. ListNode second = head;
  6. // first最终指向第k个节点
  7. for(int i = 0; i < k; i++){
  8. first = first.next;
  9. }
  10. // second与first的距离始终保持K个节点,当first遍历到最后时,second刚好在倒数第k个节点
  11. while(first != null){
  12. first = first.next;
  13. second = second.next;
  14. }
  15. return second;
  16. }
  17. }

22222 - 删除链表的倒数第N个结点(leetcode19)- 2

  1. // https://leetcode.cn/problems/remove-nth-node-from-end-of-list/
  2. class Solution {
  3. public ListNode removeNthFromEnd(ListNode head, int n) {
  4. // 重新定义头节点
  5. ListNode dummy = new ListNode(0, head);
  6. // 快指针
  7. ListNode first = head;
  8. // 慢指针
  9. ListNode second = dummy;
  10. for (int i = 0; i < n; ++i) {
  11. first = first.next;
  12. }
  13. // 当快指针到链表尾部时,慢指针到达被删除节点的上一节点
  14. while (first != null) {
  15. first = first.next;
  16. second = second.next;
  17. }
  18. // 将慢指针对应的下一个节点重新指定
  19. second.next = second.next.next;
  20. ListNode ans = dummy.next;
  21. return ans;
  22. }
  23. public ListNode removeNthFromEnd1(ListNode head, int n) {
  24. ListNode dummy = new ListNode(0, head);
  25. int length = getLength(head);
  26. ListNode cur = dummy;
  27. for (int i = 1; i < length - n + 1; ++i) {
  28. cur = cur.next;
  29. }
  30. cur.next = cur.next.next;
  31. ListNode ans = dummy.next;
  32. return ans;
  33. }
  34. // 获取链表长度
  35. public int getLength(ListNode head) {
  36. int length = 0;
  37. while (head != null) {
  38. ++length;
  39. head = head.next;
  40. }
  41. return length;
  42. }
  43. }

33333 - 合并并且去重两个有序链表

其他

两个大数相加(1)- 15

  1. // https://leetcode.cn/problems/two-sum/
  2. class Solution {
  3. public int[] twoSum(int[] nums, int target) {
  4. int[] result = new int[2];
  5. for (int i = 0; i < nums.length; i++) {
  6. for (int j = i + 1; j < nums.length; j++) {
  7. if((nums[i] + nums[j]) == target){
  8. result[0] = i;
  9. result[1] = j;
  10. return result;
  11. }
  12. }
  13. }
  14. return result;
  15. }
  16. public int[] twoSum1(int[] nums, int target) {
  17. for (int i = 0; i < nums.length; i++) {
  18. for (int j = 0; j < nums.length; j++) {
  19. if(i != j){ // 必须先判断外层循环与内层循环下标不能相同
  20. if((nums[i] + nums[j]) == target){
  21. return new int[]{i, j};
  22. }
  23. }
  24. }
  25. }
  26. return null;
  27. }
  28. }

买卖股票的最佳时机(121)- 14

  1. // https://leetcode.cn/problems/best-time-to-buy-and-sell-stock/
  2. class Solution {
  3. public int maxProfit(int prices[]) {
  4. int minprice = Integer.MAX_VALUE;
  5. int maxprofit = 0;
  6. for (int i = 0; i < prices.length; i++) {
  7. if (prices[i] < minprice) {
  8. minprice = prices[i];
  9. } else if (prices[i] - minprice > maxprofit) {
  10. maxprofit = prices[i] - minprice;
  11. }
  12. }
  13. return maxprofit;
  14. }
  15. // 执行结果超出时间限制
  16. public int maxProfit1(int[] prices) {
  17. int temp = 0;
  18. for (int i = 0; i < prices.length; i++) {
  19. for (int j = i + 1; j < prices.length; j++) {
  20. temp = Math.max(prices[j] - prices[i], temp);
  21. }
  22. }
  23. return temp;
  24. }
  25. }

爬楼梯(121)- 6

  1. // https://leetcode.cn/problems/climbing-stairs/
  2. class Solution {
  3. public int climbStairs(int n) {
  4. // 记录从1个台阶(下标为0)到n个台阶(下标为n-1)中,每个台阶所需要的方法数
  5. int[] dp = new int[n];
  6. dp[0] = 1; // 表示第一个台阶
  7. dp[1] = 2; // 表示第二个台阶
  8. // i = 2是第三个台阶,i = n-1是第n个台阶
  9. for(int i = 2; i < n; i++){
  10. dp[i] = dp[i-1] + dp[i-2];
  11. }
  12. return dp[n-1]; // 数组的最后一个值
  13. }
  14. public int climbStairs1(int n) {
  15. if(n < 3){
  16. return n;
  17. }
  18. int prePre = 1;
  19. int pre = 2;
  20. int result = 0;
  21. for (int i = 2; i < n; i++) {
  22. // f(n) = f(n-1) + f(n-2):
  23. // 若第一步爬1个台阶,则后续需要存在n-1个台阶的方法数
  24. // 若第一步爬2个台阶,则后续需要存在n-2个台阶的方法数
  25. result = pre + prePre;
  26. prePre = pre;
  27. pre = result;
  28. }
  29. return result;
  30. }
  31. }

有效的括号(20)- 20

  1. // leetcode20:有效的括号:https://leetcode.cn/problems/valid-parentheses/description/
  2. class Solution {
  3. public boolean isValid(String s) {
  4. while(true){
  5. int l = s.length();
  6. s = s.replace("()", "");
  7. s = s.replace("{}", "");
  8. s = s.replace("[]", "");
  9. if(s.length() == l){
  10. return l == 0;
  11. }
  12. }
  13. }
  14. public boolean isValid1(String s) {
  15. Stack<Character> stack = new Stack<>();
  16. stack.push(s.charAt(0));
  17. for (int i = 1; i < s.length(); i++) {
  18. char c = s.charAt(i);
  19. if(c == ')' && !stack.empty()){
  20. Character pop = stack.pop();
  21. if(pop != '('){
  22. return false;
  23. }else {
  24. continue;
  25. }
  26. }
  27. if(c == ']' && !stack.empty()){
  28. Character pop = stack.pop();
  29. if(pop != '['){
  30. return false;
  31. }else {
  32. continue;
  33. }
  34. }
  35. if(c == '}' && !stack.empty()){
  36. Character pop = stack.pop();
  37. if(pop != '{'){
  38. return false;
  39. }else {
  40. continue;
  41. }
  42. }
  43. stack.push(s.charAt(i));
  44. }
  45. return stack.empty();
  46. }
  47. }

括号生成(22)- 1

  1. // leetcode22:括号生成:https://leetcode.cn/problems/generate-parentheses/description/
  2. class Solution {
  3. public List<String> generateParenthesis(int n) {
  4. List<String> res = new ArrayList<>();
  5. getParenthesis(res, "", n, n);
  6. return res;
  7. }
  8. // str表示生成的有效括号,最后都放入res集合
  9. // left表示左括号数量、right表示右括号数量
  10. private void getParenthesis(List<String> res, String str,int left, int right) {
  11. // 当左括号与右括号数量都为0时,将生成的有效括号放入res集合
  12. if(left == 0 && right == 0 ){
  13. res.add(str);
  14. return;
  15. }
  16. if(left > right){
  17. return;
  18. }
  19. if(left > 0){
  20. getParenthesis(res, str+"(", left-1, right);
  21. }
  22. if(right > 0){
  23. getParenthesis(res, str+")", left, right-1);
  24. }
  25. }
  26. private void getParenthesis1(List<String> res, String str, int left, int right) {
  27. if(left == 0 && right == 0 ){
  28. res.add(str);
  29. return;
  30. }
  31. if(left > right){
  32. return;
  33. }else if(left == right){
  34. // 剩余左右括号数相等,下一个只能用左括号
  35. getParenthesis(res, str+"(", left-1, right);
  36. }else if(left < right){
  37. // 剩余左括号小于右括号,下一个可以用左括号也可以用右括号
  38. if(left > 0){
  39. getParenthesis(res, str+"(", left-1, right);
  40. }
  41. getParenthesis(res, str+")", left, right-1);
  42. }
  43. }
  44. }

22222 - 斐波那契数列(剑指 Offer 10- I)- 33

  1. // https://leetcode.cn/problems/fibonacci-number/
  2. // 写一个函数,输入 n ,求斐波那契(Fibonacci)数列的第 n 项(即 F(N))。
  3. // 斐波那契数列的定义如下:
  4. // F(0) = 0, F(1) = 1
  5. // F(N) = F(N - 1) + F(N - 2), 其中 N > 1
  6. // 斐波那契数列由 0 和 1 开始,之后的斐波那契数就是由之前的两数相加而得出。
  7. // 答案需要取模 1e9+7(1000000007),如计算初始结果为:1000000008,请返回 1
  8. // 输入:n = 2
  9. // 输出:1
  10. // 输入:n = 5
  11. // 输出:5
  12. class Solution {
  13. public int fib(int n) {
  14. final int MOD = 1000000007;
  15. if(n < 2){
  16. return n;
  17. }
  18. int[] dp = new int[n+1];
  19. dp[0] = 0;
  20. dp[1] = 1;
  21. for(int i = 2; i <= n; i++){
  22. dp[i] = dp[i-1] + dp[i-2];
  23. dp[i] = dp[i] % MOD;
  24. }
  25. return dp[n];
  26. }
  27. }

111111- 比较版本号(165)- 79

  1. // https://leetcode.cn/problems/compare-version-numbers/
  2. // 给你两个版本号 version1 和 version2 ,请你比较它们。
  3. // 版本号由一个或多个修订号组成,各修订号由一个 '.' 连接。每个修订号由 多位数字 组成,可能包含 前导零 。
  4. // 每个版本号至少包含一个字符。修订号从左到右编号,下标从 0 开始,最左边的修订号下标为 0 ,下一个修订号下标为 1 ,以此类推。例如,2.5.33 和 0.1 都是有效的版本号。
  5. // 比较版本号时,请按从左到右的顺序依次比较它们的修订号。比较修订号时,只需比较 忽略任何前导零后的整数值 。
  6. // 也就是说,修订号 1 和修订号 001 相等 。如果版本号没有指定某个下标处的修订号,则该修订号视为 0 。例如,版本 1.0 小于版本 1.1 ,因为它们下标为 0 的修订号相同,而下标为 1 的修订号分别为 0 和 1 ,0 < 1
  7. // 返回规则如下:
  8. // 如果 version1 > version2 返回 1,
  9. // 如果 version1 < version2 返回 -1,
  10. // 除此之外返回 0
  11. // 输入:version1 = "1.01", version2 = "1.001"
  12. // 输出:0
  13. // 解释:忽略前导零,"01" 和 "001" 都表示相同的整数 "1"
  14. // 输入:version1 = "1.0", version2 = "1.0.0"
  15. // 输出:0
  16. // 解释:version1 没有指定下标为 2 的修订号,即视为 "0"
  17. class Solution {
  18. // 时间与空间复杂度均为:O(n+m)
  19. public int compareVersion1(String version1, String version2) {
  20. String[] v1 = version1.split("\\.");
  21. String[] v2 = version2.split("\\.");
  22. for (int i = 0; i < v1.length || i < v2.length; i++) {
  23. // 遍历每个元素时,将v1Vaule与v2Vaule均重新赋值为0,因为此时v1 或 v2已经遍历完,要用0代替与另一个的值进行比较
  24. // 如果版本号没有指定某个下标处的修订号,则该修订号视为0
  25. int v1Value = 0, v2Value = 0;
  26. // 依次遍历v1 与 v2,取出对应元素进行比较
  27. if (i < v1.length) v1Value = Integer.parseInt(v1[i]);
  28. if (i < v2.length) v2Value = Integer.parseInt(v2[i]);
  29. if (v1Value > v2Value) return 1;
  30. if (v1Value < v2Value) return -1;
  31. }
  32. return 0;
  33. }
  34. // 时间复杂度:O(n+m)、空间复杂度:O(1)
  35. public int compareVersion(String version1, String version2) {
  36. int v1Len = version1.length(), v2Len = version2.length();
  37. int v1Index = 0, v2Index = 0;
  38. while (v1Index < v1Len || v2Index < v2Len) {
  39. int v1Value = 0;
  40. for (; v1Index < v1Len && version1.charAt(v1Index) != '.'; v1Index++) {
  41. v1Value = v1Value * 10 + (version1.charAt(v1Index) - '0');
  42. }
  43. v1Index++; // 上一个for循环后就是点号,此步骤目的是跳过点号
  44. int v2Value = 0;
  45. for (; v2Index < v2Len && version2.charAt(v2Index) != '.'; v2Index++) {
  46. v2Value = v2Value * 10 + (version2.charAt(v2Index) - '0');
  47. }
  48. v2Index++; // 跳过点号
  49. if (v1Value != v2Value) {
  50. return v1Value > v2Value ? 1 : -1;
  51. }
  52. }
  53. return 0;
  54. }
  55. }

11111 - x的n次方(50)- 33

  1. // https://leetcode.cn/problems/powx-n/description/
  2. // 实现 pow(x, n) ,即计算x的整数n次幂函数(即,x^n )
  3. class Solution {
  4. public double myPow(double x, int n) {
  5. if(n == 0) return 1;
  6. if(n == 1) return x;
  7. if(x == 0) return 0;
  8. if(x == 1) return 1;
  9. // 处理负数越界的问题
  10. if (n < 0){
  11. if(n == Integer.MIN_VALUE){
  12. if(x < 0) return 1;
  13. else return 0;
  14. }
  15. return 1 / myPow(x, -n);
  16. }
  17. // 需要进行奇偶判断,否则执行出错StackOverflowError
  18. if (n % 2 == 1){
  19. return x * myPow(x, n-1);
  20. }
  21. return myPow(x*x, n/2);
  22. }
  23. // 超出时间限制
  24. public double myPow1(double x, int n) {
  25. if (n < 0 && n == Integer.MIN_VALUE){
  26. if(x < 0) return 1;
  27. else if(x == 1) return 1;
  28. else return 0;
  29. }
  30. if(n == 0) return 1;
  31. if(n == 1) return x;
  32. if(x == 0) return 0;
  33. if(x == 1) return x;
  34. double result = x;
  35. for(int i = 1; i < Math.abs(n); i++){
  36. result = result * x;
  37. }
  38. return n > 0 ? result : 1 / result;
  39. }
  40. }

11111 - 复原 IP 地址(93)- 95

  1. // https://leetcode.cn/problems/restore-ip-addresses/
  2. // 有效 IP 地址 正好由四个整数(每个整数位于 0 到 255 之间组成,且不能含有前导 0),整数之间用 '.' 分隔
  3. // 给定一个只包含数字的字符串 s ,用以表示一个 IP 地址,返回所有可能的有效 IP 地址,这些地址可以通过在 s 中插入 '.' 来形成。你 不能 重新排序或删除 s 中的任何数字。你可以按 任何 顺序返回答案
  4. // 输入:s = "101023"
  5. // 输出:["1.0.10.23","1.0.102.3","10.1.0.23","10.10.2.3","101.0.2.3"]
  6. class Solution {
  7. List<String> result = new ArrayList<String>();
  8. Deque<String> path = new ArrayDeque<>(4);
  9. public List<String> restoreIpAddresses(String s) {
  10. process(s, 0, 4);
  11. return result;
  12. }
  13. // start表示当前索引位置,reside表示剩余段数
  14. public void process(String s, int start, int reside){
  15. // 终止条件
  16. if(start == s.length()){
  17. // 当变量到最后一个字符 且 剩余段数为0时,将此时的path添加到结果集中
  18. if(reside == 0){
  19. result.add(String.join(".", path));
  20. }
  21. return;
  22. }
  23. for(int i = start; i < start + 3 && i < s.length(); i++){
  24. // 若字符串剩余长度 大于 剩余分段所需最大长度,表明先前的分段不合理,最后会存在剩余字符
  25. if(s.length() - i > reside * 3){
  26. continue;
  27. }
  28. // 截取的字符串满足条件
  29. if(judgeNumber(s, start, i)){
  30. // 截取部分字符添加到path中
  31. String cur = s.substring(start, i+1);
  32. path.addLast(cur);
  33. // 纵向递归
  34. process(s, i+1, reside-1);
  35. path.removeLast();
  36. }
  37. }
  38. }
  39. // 判断截取的字符串是否满足要求
  40. public boolean judgeNumber(String s, int left, int right){
  41. int len = right - left + 1;
  42. // 当前为0开头 且 长度大于1的数字需要剪枝
  43. if(s.charAt(left) == '0' && len > 1){
  44. return false;
  45. }
  46. // 将当前截取的字符串转化成数字
  47. int res = Integer.parseInt(s.substring(left, right+1));
  48. // 判断截取到的数字是否符合
  49. return res >= 0 && res <= 255;
  50. }
  51. }

33333 - 分发糖果(135)- 29

圆圈中最后剩下的数字(剑指 Offer 62) - 29

  1. https://leetcode.cn/problems/yuan-quan-zhong-zui-hou-sheng-xia-de-shu-zi-lcof/
  2. 1-13号纸牌,第一个放在牌堆底部,第二个放在桌子上,以此类推,当手里没牌时桌面上牌的顺序
  3. (约瑟夫环或者叫丢手绢问题 力扣 剑指 Offer 62. 圆圈中最后剩下的数字)
  1. 微信拼手气红包,输入两个参数:人数、金额数,输出每个人所得的红包金额
  2. 有序序列插入数据索引
  3. 笛卡尔坐标系给五个坐标挑出欧几里得距离最近的一对
  4. kmp了解吗
  5. 哈夫曼编码了解吗?
  6. 关键路径了解吗
  7. 输入3个数,判断是否能构成直角三角形(用测试的思想)
  8. 存一堆无序数据用链表还是队列
  9. 实现多线程从A、B、C三个文件中读取数据并写到log.txt中

    理论

    快速排序

  10. 快速排序的实现的原理:

    1. 快速排序实现的重点在于数组的拆分,通常我们将数组的第一个元素定义为比较元素,然后将数组中小于比较元素的数放到左边,将大于比较元素的放到右边,这样我们就将数组拆分成了左右两部分:小于比较元素的数组;大于比较元素的数组。我们再对这两个数组进行同样的拆分,直到拆分到不能再拆分,数组就自然而然地以升序排列了
  11. 快速排序的过程:
    1. 先找一个基准,将这个基准赋值给临时变量tmp中
    2. 从后往前找第一个比基准小的数据赋值到i位置
    3. 从前往后找第一个比基准大的数据赋值到j位置
    4. 重复步骤1和步骤2直到i和j相遇,然后将tmp的值赋给i和j相遇的位置
    5. 将基准左边和基准右边的数据继续按照步骤1,2,3,4进行,直到数据全部排完。
  12. 时间复杂度:O(nlogn)。空间复杂度:O(logn)。快速排序是一个不稳定的排序算法

    堆排序

  13. 堆排序是指利用堆(heap)这种数据结构所设计的一种排序算法。堆是一个近似完全二叉树的结构,并同时满足堆积的性质:即子节点的键值或索引总是小于(或者大于)它的父节点

  14. 大根堆/大顶堆:每个节点的值均大于等于其左右孩子节点的值;
    小根堆/小顶堆:每个节点的值均小于等于其左右孩子节点的值。
  15. 大根堆:nums[i] >= nums[2i+1] & nums[i] >= nums[2i+2]
    小根堆:nums[i] <= nums[2i+1] & nums[i] <= nums[2i+2]
  16. 对于「升序排列」数组,需用到大根堆
    对于「降序排列」数组,则需用到小根堆

    数组和链表的区别

  17. 数组静态分配内存,链表动态分配内存;

  18. 数组在内存中连续,链表不连续;
  19. 数组元素在栈区,链表元素在堆区;
  20. 数组利用下标定位,时间复杂度为O(1),链表定位元素时间复杂度O(n);
  21. 数组插入或删除元素的时间复杂度O(n),链表的时间复杂度O(1)。

    递归

  22. 递归的原理:一个大问题可以分解成几个小问题,其中有的小问题可以直接实现,另一部分小问题与大问题的实现方式相同,从而进入循环,递归到最后会有一个直接实现方式,即递归出口

  23. 递归三要素:

    1. 确定递归函数的参数和返回值:确定递归过程中需要处理的参数,明确每次递归的返回值进而确定递归函数的返回类型
    2. 确定递归终止条件,即函数return的出口:终止条件写的不对,操作系统的内存栈一定会溢出,毕竟递归也是有限制的
    3. 确定单层递归的逻辑:明确每次递归要进行什么操作

      栈、堆和队列的区别

  24. 栈:栈是一种线性的数据结构,读取规则是先进后出。栈中的数据占用的内存空间的大小是确定的,便于代码执行时的入栈、出栈操作,并由系统自动分配和自动释放内存可以及时得到回收,相对于堆来说,更加容易管理内存空间。

  25. 堆:堆是一种树形数据结构,读取相对复杂。堆是动态分配内存,内存大小不一,也不会自动释放。栈中的数据长度不定,且占空间比较大。便于开辟内存空间,更加方便存储。
  26. 堆栈内存分配:程序运行时,每个线程分配一个栈每个进程分配一个堆。也就是说,栈是线程独占的,堆是线程共用的。此外,栈创建的时候,大小是确定的,数据超过这个大小,就发生stack overflow错误,而堆的大小是不确定的,需要的话可以不断增加。
  27. 队列是一种先进先出的数据结构。 队列在列表的末端增加项,在首端移除项。它允许在表的首端(队列头)进行删除操作,在表的末端(队列尾)进行插入操作
  28. 栈是一种后进先出的数据结构,也就是说最新添加的项最早被移出;它是一种运算受限的线性表,只能在栈顶进行插入和删除操作。向一个栈插入新元素叫入栈(进栈),就是把新元素放入到栈顶的上面,成为新的栈顶;从一个栈删除元素叫出栈,就是把栈顶的元素删除掉,相邻的成为新栈顶
  29. 应用场景:

    1. 栈可以用于字符匹配,数据反转等场景
    2. 队列可以用于任务队列,共享打印机等场景
    3. 堆可以用于优先队列,堆排序等场景

      平衡二叉树和红黑树的区别

  30. 平衡二叉树树有以下规则:

    1. 规则1:每个节点最多只有两个子节点(二叉)
    2. 规则2:每个节点的值比它的左子树所有的节点大,比它的右子树所有节点小(有序)
    3. 规则3:每个节点左子树的高度与右子树高度之差的绝对值不超过1
  31. 红黑树的规则:它一种特殊的二叉查找树
    1. 规则1:每个节点不是黑色就是红色
    2. 规则2:根节点为黑色
    3. 规则3:红色节点的父节点和子节点不能为红色
    4. 规则4:所有的叶子节点都是黑色(空节点视为叶子节点NIL)
    5. 规则5:每个节点到叶子节点的每个路径黑色节点的个数都相等
  32. 平衡二叉树和红黑树的区别:
    1. 平衡二叉树的左右子树的高度差绝对值不超过1,但是红黑树在某些时刻可能会超过1,只要符合红黑树的五个条件即可。
    2. 二叉树只要不平衡就会进行旋转,而红黑树不符合规则时,有些情况只用改变颜色不用旋转,就能达到平衡。
  33. 红黑树的时间复杂度为:O(logn)