代码重构与新增解决方案:

-重构`LeetCode5`、`LeetCode15`与`LeetCode53`,优化代码结构并引入新测试用例。
- 在`LeetCode80`与`LeetCode88`中添加新解法,提升数组操作效率。
- 为`LeetCode124`、`LeetCode146`以及`LeetCode189`等题新增解决方案,丰富算法实现。
- 在`LeetCode274`、`LeetCode380`中引入新思路,提高算法效率。

所有新增代码均包含单元测试,保证代码质量与可验证性。
This commit is contained in:
whaifree 2024-09-16 19:38:34 +08:00
parent a75259b346
commit 093947705e
11 changed files with 548 additions and 2 deletions

View File

@ -23,13 +23,19 @@ public class LeetCode169
/** /**
* 遍历每个元素 * 遍历每个元素
* count 为现在出现最多的数 * count 为现在出现最多的数
* - 如果count = 0 * - 如果count = 0 (表示发生了是和不是的变化)
* - 这个元素出现的次数>=之前元素出现的个数 * - 这个元素出现的次数>=之前元素出现的个数
* 所以基准变为这个元素 * 所以基准变为这个元素
* count = item == base : 1:-1 * count = item == base : 1:-1
* *
* 如果是这个元素+1,不是这个元素-1 * 如果是这个元素+1,不是这个元素-1
* *
* cge5 cge5 cge7
* 1 2 1 2 1 0 1 0 1 2 1 0 1 2 3 4
* [7, 7, 5, 7, 5, 1 | 5, 7 | 5, 5, 7, 7 | 7, 7, 7, 7]
* 在遍历到数组中的第一个元素以及每个在 | 之后的元素时candidate 都会因为 count 的值变为 0 而发生改变最后一次 candidate 的值从 5 变为 7也就是这个数组中的众数
*
*
* @param nums * @param nums
* @return * @return
*/ */

View File

@ -0,0 +1,58 @@
package cn.whaifree.leetCode.Array;
import org.junit.Test;
import java.util.Arrays;
/**
* @version 1.0
* @Author whai文海
* @Date 2024/9/16 12:15
* @注释
*/
public class LeetCode189 {
@Test
public void test()
{
int[] nums = new int[]{-1};
new Solution1().rotate(nums, 3);
System.out.println(Arrays.toString(nums));
}
class Solution {
public void rotate(int[] nums, int k) {
int[] newNums = new int[nums.length];
for (int i = 0; i < newNums.length; i++) {
newNums[(i + k) % nums.length] = nums[i];
}
System.arraycopy(newNums, 0, nums, 0, nums.length);
}
}
class Solution1 {
public void rotate(int[] nums, int k) {
k %= nums.length;
reverse(nums, 0, nums.length - 1);
reverse(nums, 0, k - 1);
reverse(nums, k, nums.length - 1);
}
public void reverse(int[] nums, int start, int end) {
while (start < end) {
swap(nums, start, end);
start++;
end--;
}
}
public void swap(int[] nums, int i, int j) {
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
}
}

View File

@ -0,0 +1,35 @@
package cn.whaifree.leetCode.Array;
import org.junit.Test;
import java.util.Arrays;
/**
* @version 1.0
* @Author whai文海
* @Date 2024/9/16 17:17
* @注释
*/
public class LeetCode274 {
@Test
public void test()
{
int[] nums = new int[]{1,3,1};
System.out.println(new Solution().hIndex(nums));
}
class Solution {
public int hIndex(int[] citations) {
Arrays.sort(citations);
for (int i = 0; i < citations.length; i++) {
int h = citations.length - i;
if (citations[i] >= h) {
return h;
}
}
return 0;
}
}
}

View File

@ -0,0 +1,61 @@
package cn.whaifree.leetCode.Array;
import org.junit.Test;
/**
* @version 1.0
* @Author whai文海
* @Date 2024/9/16 16:23
* @注释
*/
public class LeetCode80 {
@Test
public void test() {
int[] nums = new int[]{0, 0, 1, 1, 1, 1, 2, 3, 3};
System.out.println(new Solution().removeDuplicates(nums));
}
class Solution {
/**
* 双指针
* - 跳跃判断如果不一样就让left向前并赋值
*
* @param nums
* @return
*/
public int removeDuplicates(int[] nums) {
if (nums.length < 3) return nums.length;
int leftSlow = 0;
int rightFast = 2;
while (rightFast < nums.length) {
if (nums[rightFast] != nums[leftSlow]) {
nums[leftSlow + 2] = nums[rightFast];
leftSlow++;
}
rightFast++;
}
return leftSlow + 2;
}
}
class Solution1 {
/**
*
*
* @param nums
* @return
*/
public int removeDuplicates(int[] nums) {
// 数组中的一号和二号元素肯定不用删除
int index = 2;
for(int i = 2 ; i < nums.length ; i++) {
if(nums[i] != nums[index-2]) {
nums[index++] = nums[i];
}
}
return index;
}
}
}

View File

@ -0,0 +1,48 @@
package cn.whaifree.leetCode.Array;
import org.junit.Test;
import java.util.Arrays;
/**
* @version 1.0
* @Author whai文海
* @Date 2024/9/16 16:11
* @注释
*/
public class LeetCode88 {
@Test
public void test()
{
int[] nums1 = new int[]{1,2,3,0,0,0};
int[] nums2 = new int[]{2,5,6};
new Solution().merge(nums1, 3, nums2, 3);
System.out.println(Arrays.toString(nums1));
}
class Solution {
public void merge(int[] nums1, int m, int[] nums2, int n) {
int index = 0;
int[] res = new int[nums1.length];
int index1 = 0;
int index2 = 0;
while (index1 < m && index2 < n) {
if (nums1[index1] < nums2[index2]) {
res[index++] = nums1[index1++];
}else {
res[index++] = nums2[index2++];
}
}
while (index1 < m) {
res[index++] = nums1[index1++];
}
while (index2 < n) {
res[index++] = nums2[index2++];
}
System.arraycopy(res, 0, nums1, 0, index);
}
}
}

View File

@ -0,0 +1,76 @@
package cn.whaifree.leetCode.Hash;
import org.junit.Test;
import java.util.*;
/**
* @version 1.0
* @Author whai文海
* @Date 2024/9/16 19:18
* @注释
*/
public class LeetCode380 {
@Test
public void test()
{
// ["RandomizedSet","remove","remove","insert","getRandom","remove","insert"]
// [[],[0],[0],[0],[],[0],[0]]
RandomizedSet randomizedSet = new RandomizedSet();
randomizedSet.remove(0);
randomizedSet.remove(0);
randomizedSet.insert(0);
randomizedSet.getRandom();
randomizedSet.remove(0);
randomizedSet.insert(0);
}
class RandomizedSet {
List<Integer> list;
Map<Integer, Integer> map;
Random random;
public RandomizedSet() {
list = new ArrayList<>();
map = new HashMap<>();
random = new Random();
}
public boolean insert(int val) {
// 存在返回false
if (map.containsKey(val)) {
return false;
}
int size = list.size();
list.add(size, val);
map.put(val, size);
return true;
}
public boolean remove(int val) {
if (!map.containsKey(val)) {
return false;
}
Integer idx = map.get(val); // 删除的元素index
Integer lastElement = list.get(list.size() - 1); // 最后一个元素的值
// 更新最后一个元素覆盖原来的list
list.set(idx, lastElement);
map.put(lastElement, idx);
// 删除元素放最后
list.remove(list.size() - 1);
map.remove(val);
return true;
}
public int getRandom() {
return list.get(random.nextInt(list.size()));
}
}
}

View File

@ -0,0 +1,56 @@
package cn.whaifree.leetCode.Tree;
import cn.whaifree.leetCode.model.TreeNode;
import org.junit.Test;
/**
* @version 1.0
* @Author whai文海
* @Date 2024/9/16 15:05
* @注释
*/
public class LeetCode124 {
@Test
public void test()
{
TreeNode treeNode = TreeNode.constructTreeByArray(1, 2, 3);
System.out.println(new Solution().maxPathSum(treeNode));
}
class Solution {
/**
* f
* a
* b c
* <p>
* a有可能的路径
* 1. f a c
* 2. f a b
* 3. b a c 不包含父亲节点 用b+a+c与max判断
*
* @param root
* @return
*/
int max = Integer.MIN_VALUE;
public int maxPathSum(TreeNode root) {
maxPath(root);
return max;
}
public int maxPath(TreeNode root) {
if (root == null) {
return 0;
}
int left = maxPath(root.left);
int right = maxPath(root.right);
if (left < 0) {
left = 0;
}
if (right < 0) {
right = 0;
}
max = Math.max(max, left + right + root.val); // 如果是 b a c 既没有用父亲节点
return Math.max(left, right) + root.val;
}
}
}

View File

@ -0,0 +1,80 @@
package cn.whaifree.redo.redo_all_240721;
import org.junit.Test;
import java.util.LinkedHashMap;
/**
* @version 1.0
* @Author whai文海
* @Date 2024/9/16 15:46
* @注释
*/
public class LeetCode146 {
@Test
public void test()
{
// LRUCache cache = new LRUCache(2);
// cache.put(1, 1);
// cache.put(2, 2);
// System.out.println(cache.get(1));
// cache.put(3, 3);
// System.out.println(cache.get(2));
// cache.put(4, 4);
// System.out.println(cache.get(1));
// System.out.println(cache.get(3));
// System.out.println(cache.get(4));
/**
* ["LRUCache","put","put","put","put","get","get"]
* [[2],[2,1],[1,1],[2,3],[4,1],[1],[2]]
*
*/
LRUCache cache1 = new LRUCache(2);
cache1.put(2, 1);
cache1.put(1, 1);
cache1.put(2, 3);
cache1.put(4, 1);
System.out.println(cache1.get(1));
System.out.println(cache1.get(2));
}
class LRUCache {
LinkedHashMap<Integer, Integer> map = new LinkedHashMap<>(); // 有序
int defaultSize = 0 ;
public LRUCache(int capacity) {
defaultSize = capacity;
}
public int get(int key) {
if (map.containsKey(key)) {
Integer v = map.get(key);
map.remove(key);
map.put(key, v);
return v;
}
return -1;
}
public void put(int key, int value) {
if (map.containsKey(key)) {
map.put(key, value);
get(key);
return;
}
map.put(key, value);
if (map.size() > defaultSize) {
for (Integer i : map.keySet()) {
map.remove(i);
break;
}
}
}
}
}

View File

@ -1,5 +1,7 @@
package cn.whaifree.redo.redo_all_240721; package cn.whaifree.redo.redo_all_240721;
import org.junit.Test;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
@ -31,7 +33,7 @@ public class LeetCode15 {
int mid = left + 1; int mid = left + 1;
int right = len - 1; int right = len - 1;
if (left > 0 && nums[left] == nums[left - 1]) { if (left > 0 && nums[left] == nums[left - 1]) {
break; continue;
} }
while (mid < right) { while (mid < right) {
int sum = nums[left] + nums[mid] + nums[right]; int sum = nums[left] + nums[mid] + nums[right];
@ -55,4 +57,53 @@ public class LeetCode15 {
} }
return res; return res;
} }
@Test
public void test() {
System.out.println(new Solution().threeSum(new int[]{-1,0,1,2,-1,-4,-2,-3,3,0,4}));
}
class Solution {
List<List<Integer>> res = null;
public List<List<Integer>> threeSum(int[] nums) {
res = new ArrayList<>();
threeSum(nums, 0);
return res;
}
public void threeSum(int[] nums, int sum) {
Arrays.sort(nums);
int left = 0;
while (left < nums.length - 2) {
int right = nums.length - 1;
if (left > 0 && nums[left] == nums[left - 1]) {
left++;
continue;
}
int mid = left + 1;
while (mid < right) {
int nowSum = nums[left] + nums[mid] + nums[right];
if (nowSum == sum) {
res.add(Arrays.asList(nums[left], nums[mid], nums[right]));
while (mid < right && nums[mid] == nums[mid + 1]) { // mid是往右探头
mid++;
}
while (mid < right && nums[right] == nums[right - 1]) { // right是往左探头
right--;
}
mid++;
right--;
} else if (nowSum > sum) {
right--;
} else {
mid++;
}
}
left++;
}
}
}
} }

View File

@ -0,0 +1,43 @@
package cn.whaifree.redo.redo_all_240721;
import org.junit.Test;
/**
* @version 1.0
* @Author whai文海
* @Date 2024/9/16 15:29
* @注释
*/
public class LeetCode5 {
@Test
public void test()
{
System.out.println(new Solution().longestPalindrome("babad"));
}
class Solution {
public String longestPalindrome(String s) {
String maxHuiWen = "";
for (int i = 0; i < s.length(); i++) {
String huiWenA = getHuiWen(s, i, i);
String huiWenB = getHuiWen(s, i, i + 1);
if (huiWenA.length() > maxHuiWen.length()) {
maxHuiWen = huiWenA;
}
if (huiWenB.length() > maxHuiWen.length()) {
maxHuiWen = huiWenB;
}
}
return maxHuiWen;
}
public String getHuiWen(String s, int start, int end) {
while (start >= 0 && end < s.length() &&s.charAt(start) == s.charAt(end)) {
start--;
end++;
}
return s.substring(start + 1, end);
}
}
}

View File

@ -2,6 +2,8 @@ package cn.whaifree.redo.redo_all_240721;
import org.junit.Test; import org.junit.Test;
import java.util.Arrays;
/** /**
* @version 1.0 * @version 1.0
* @Author whai文海 * @Author whai文海
@ -72,4 +74,34 @@ public class LeetCode53 {
return max; return max;
} }
} }
@Test
public void test2()
{
int[] nums = new int[]{-2,1,-3,4,-1,2,1,-5,4};
Solution2 solution = new Solution2();
System.out.println(solution.maxSubArray(nums));
}
class Solution2 {
/**
* dp[i] 表述i位置的最大子数组的和
* @param nums
* @return
*/
public int maxSubArray(int[] nums) {
int[] dp = new int[nums.length];
dp[0] = nums[0];
for (int i = 1; i < nums.length; i++) {
if (dp[i - 1] > 0 && dp[i - 1] + nums[i] > 0) {
// 不要拖后腿
dp[i] = dp[i - 1] + nums[i];
} else {
dp[i] = nums[i];
}
}
return Arrays.stream(dp).max().getAsInt();
}
}
} }