当前位置: 首页 > news >正文

LeetCode 热题100题解(Java版本)

一、哈希

1、两数之和
https://leetcode.cn/problems/two-sum/?envType=study-plan-v2&envId=top-100-liked

使用HashMap,遍历数组,判断当前元素的“补数”是否存在,如果存在直接返回结果,否则在Map中记录当前元素及其下标。

时间复杂度 O(n)
空间复杂度 O(n)

class Solution {public int[] twoSum(int[] nums, int target) {Map<Integer, Integer> map = new HashMap<>(nums.length);for(int i=0; i < nums.length; i++){int x = target-nums[i];if(map.containsKey(x)){return new int[]{map.get(x), i};}else{map.put(nums[i], i);}}return null;}
}
2、字母异位词分组
https://leetcode.cn/problems/group-anagrams/description/?envType=study-plan-v2&envId=top-100-liked

computeIfAbsent 方法是 Java 中 Map 接口提供的一个方法,用于在 Map 中不存在指定 key 的情况下,根据指定的函数计算一个值并将其存储到 Map 中。具体来说,该方法接收两个参数:key 和一个函数。如果 Map 中不存在指定的 key,则会调用该函数计算一个值,并将该值与指定的 key 关联存储到 Map 中。如果指定的 key 已经存在于 Map 中,则该方法不会执行任何操作。这个方法可以用于避免手动检查 key 是否存在,简化代码逻辑。

Map接口的values()方法返回一个包含Map中所有值的Collection。这个Collection是Map中所有值的视图,任何对该Collection的修改都会反映到原始Map中。

时间复杂度 O(n)
空间复杂度 O(n)

class Solution {static class ArrayKey{int[] key = new int[26];public boolean equals(Object obj){if(obj == null || !getClass().equals(obj.getClass()))return false;if(key == obj)return true;ArrayKey arrayKey = (ArrayKey) obj;return Arrays.equals(key, arrayKey.key);}public int hashCode(){return Arrays.hashCode(key);}public ArrayKey(String str){for(char c : str.toCharArray()){key[c - 'a']++;}}}public List<List<String>> groupAnagrams(String[] strs) {Map<ArrayKey, List<String>> map = new HashMap<>();for(String s : strs){ArrayKey arrayKey = new ArrayKey(s);List<String> list = map.computeIfAbsent(arrayKey, key -> new ArrayList<>());list.add(s);}return new ArrayList<>(map.values());}
}
3、最长连续序列
https://leetcode.cn/problems/longest-consecutive-sequence/description/?envType=study-plan-v2&envId=top-100-liked

先使用HashSet去重,如果对当前元素x存在x-1,那么肯定从x-1开始算序列长度会更长,所以当x-1存在时,就跳过x,去计算x-1。

时间复杂度 O(n)
空间复杂度 O(n)

class Solution {public int longestConsecutive(int[] nums) {Set<Integer> set = new HashSet<>();for(int n : nums){set.add(n);}int ans = 0;for(Integer x : set){if(!set.contains(x-1)){int cur = x;int len = 1;while(set.contains(cur+1)){cur++;len++;}ans = Math.max(ans, len);}}return ans;}
}

二、双指针

1、移动零
https://leetcode.cn/problems/move-zeroes/description/?envType=study-plan-v2&envId=top-100-liked

不用双指针,先将非0数重新放入nums,最后放入0。

时间复杂度 O(n)
空间复杂度 O(1)

class Solution {public void moveZeroes(int[] nums) {int pos = 0;for(int x : nums){if(x != 0){nums[pos++] = x;}}while(pos < nums.length)nums[pos++] = 0;}
}
2、盛最多水的容器
https://leetcode.cn/problems/container-with-most-water/description/?envType=study-plan-v2&envId=top-100-liked

时间复杂度O(logn)
空间复杂度 O(1)

class Solution {public int maxArea(int[] height) {int l = 0, r = height.length - 1;int max = 0;while(l < r){// 计算之间的面积int sum = Math.min(height[l], height[r]) * (r - l);if(sum > max) max = sum;// 移动柱子,尽量让待计算的高度更高if(height[l] <= height[r]){l++;}else{r--;}}return max;}
}
3、三数之和
https://leetcode.cn/problems/3sum/description/?envType=study-plan-v2&envId=top-100-liked

排序+双指针

时间 O(n^2)
空间 O(n)

class Solution {public List<List<Integer>> threeSum(int[] nums) {Arrays.sort(nums);int n = nums.length;List<List<Integer>> ans = new ArrayList<>();for(int i = 0; i < n-2; i++){// 去重if(i > 0 && nums[i] == nums[i-1])continue;List<List<Integer>> res = fun(nums, i+1, n-1, nums[i], -nums[i]);ans.addAll(res);}return ans;}public List<List<Integer>> fun(int[] nums, int left, int right, int num, int target){List<List<Integer>> ans = new ArrayList<>();int l = left, r = right;while(l < r){int sum = nums[l]+nums[r];if(sum == target){List<Integer> list = new ArrayList<>();list.add(num);list.add(nums[l]);list.add(nums[r]);ans.add(list);// 去重while(l < r && nums[l] == nums[l+1]){l++;}l++;while(l < r && nums[r] == nums[r-1]){r--;}r--;}else if(sum < target){l++;}else{r--;}}return ans;}
}
4、接雨水
https://leetcode.cn/problems/trapping-rain-water/?envType=study-plan-v2&envId=top-100-liked

时间O(n)
空间O(n)

class Solution {public int trap(int[] height) {int n = height.length;int[] left = new int[n];int[] right = new int[n];left[0] = height[0];for(int i = 1; i < n; i++){left[i] = Math.max(height[i], left[i-1]);}right[n-1] = height[n-1];for(int i = n-2; i>= 0; i--){right[i] = Math.max(height[i], right[i+1]);}int sum = 0;for(int i = 0; i < n; i++){int x = Math.min(left[i], right[i]) - height[i];if(x > 0)sum += x;}return sum;}
}

三、滑动窗口

1、无重复字符的最长子串
https://leetcode.cn/problems/longest-substring-without-repeating-characters/description/?envType=study-plan-v2&envId=top-100-liked

时间O(n)
空间O(|S|)

如果[i, j]不重复,那么[i+1, j]不重复

class Solution {public int lengthOfLongestSubstring(String s) {int n = s.length();Set<Character> set = new HashSet<>();int j = 0, cnt = 0;for(int i = 0; i < n; i++){if(i != 0){set.remove(s.charAt(i-1));}while(j < n && !set.contains(s.charAt(j))){set.add(s.charAt(j));j++;}cnt = Math.max(cnt, j - i);}return cnt;}
}
2、找到字符串中所有字母异位词
https://leetcode.cn/problems/find-all-anagrams-in-a-string/description/?envType=study-plan-v2&envId=top-100-liked

使用Hash,其实就是暴力,但是容易理解。

class Solution {static class ArrayKey{int[] key = new int[26];public ArrayKey(String s){for(char c : s.toCharArray()){key[c - 'a']++;}}public boolean equals(Object o){if(o == null || !o.getClass().equals(this.getClass()))return false;if(o == this)return true;ArrayKey arrayKey = (ArrayKey)o;return Arrays.equals(this.key, arrayKey.key);}public int hashCode(){return Arrays.hashCode(key);}}public List<Integer> findAnagrams(String s, String p) {List<Integer> ans = new ArrayList<>();int len1 = s.length();int len2 = p.length();ArrayKey key = new ArrayKey(p);for(int i = 0; i <= len1-len2; i++){String str = s.substring(i, i+len2);ArrayKey t = new ArrayKey(str);if(key.equals(t)){ans.add(i);}}return ans;}
}

四、子串

1、和为 K 的子数组
https://leetcode.cn/problems/subarray-sum-equals-k/description/?envType=study-plan-v2&envId=top-100-liked

前缀和+HashMap

class Solution {public int subarraySum(int[] nums, int k) {int cnt = 0;int n = nums.length;int pre = 0;HashMap<Integer, Integer> map = new HashMap<>();map.put(0, 1);for(int i = 0; i < n; i++){pre += nums[i];if(map.containsKey(pre - k)){cnt += map.get(pre - k);}map.put(pre, map.getOrDefault(pre, 0) + 1);}return cnt;}
}
2、滑动窗口最大值
https://leetcode.cn/problems/sliding-window-maximum/description/?envType=study-plan-v2&envId=top-100-liked

使用优先队列

class Solution {public int[] maxSlidingWindow(int[] nums, int k) {PriorityQueue<int[]> pq = new PriorityQueue<>(new Comparator<int[]>(){public int compare(int[] pair1, int[] pair2){return pair1[0] != pair2[0] ? pair2[0]-pair1[0] : pair2[1]-pair1[1];}});for(int i = 0; i < k; i++){pq.offer(new int[]{nums[i], i});}int[] ans = new int[nums.length-k+1];ans[0] = pq.peek()[0];int x = 1;for(int i = k; i < nums.length; i++){pq.offer(new int[]{nums[i], i});// 最大值不在窗口内了,就出队while(pq.peek()[1] <= i-k){pq.poll();}ans[x++] = pq.peek()[0];}return ans;}
}
import java.util.*;public class Solution {public ArrayList<Integer> maxInWindows (int[] num, int size) {if(num.length == 0 || size > num.length || size == 0){return new ArrayList<Integer>();}ArrayList<Integer> ans = new ArrayList<>(num.length-size+1);// 使用Lambda表达式PriorityQueue<int[]> pq = new PriorityQueue<>((arr1, arr2) ->arr1[0] != arr2[0] ? arr2[0] - arr1[0] : arr2[1] - arr1[1]);for(int i = 0; i < size; i++){pq.offer(new int[]{num[i], i});}ans.add(pq.peek()[0]);for(int i = size; i < num.length; i++){pq.offer(new int[]{num[i], i});while(pq.peek()[1] <= i-size){pq.poll();}ans.add(pq.peek()[0]);}return ans;}
}

五、普通数组

1、最大子数组和
https://leetcode.cn/problems/maximum-subarray/description/?envType=study-plan-v2&envId=top-100-liked
class Solution {// public int maxSubArray(int[] nums) {//     int n = nums.length;//     int[] dp = new int[n];//     dp[0] = nums[0];//     int ans = dp[0];//     for(int i = 1; i < n; i++){//         dp[i] = Math.max(dp[i-1] + nums[i], nums[i]);//         ans = Math.max(ans, dp[i]);//     }//     return ans;// }public int maxSubArray(int[] nums) {if(nums.length ==1)return nums[0];int cur = 0;int ans = Integer.MIN_VALUE;for(int i = 0; i < nums.length; i++){cur = cur+nums[i];ans = Math.max(ans, cur);if(cur <= 0){cur = 0;continue;}}return ans;}
}
2、合并区间
https://leetcode.cn/problems/merge-intervals/description/?envType=study-plan-v2&envId=top-100-liked

时间O(nlogn),主要是排序

class Solution {public int[][] merge(int[][] intervals) {int len = intervals.length;//Arrays.sort(intervals, (a, b) -> Integer.compare(a[0], b[0]));Arrays.sort(intervals, new Comparator<int[]>() {public int compare(int[] interval1, int[] interval2) {return interval1[0] - interval2[0];}});List<int[]> ans = new LinkedList<>();ans.add(intervals[0]);for(int i = 1; i < len; i++){if(intervals[i][0] <= ans.getLast()[1]){int start = ans.getLast()[0];int end = Math.max(intervals[i][1], ans.getLast()[1]);ans.removeLast();ans.add(new int[]{start,end});}else{ans.add(intervals[i]);}}return ans.toArray(new int[ans.size()][]);}
}
3、轮转数组
https://leetcode.cn/problems/rotate-array/description/?envType=study-plan-v2&envId=top-100-liked

使用一个额外的数组

class Solution {public void rotate(int[] nums, int k) {int n = nums.length;int[] t = new int[n];for(int i = 0; i < n; i++){t[(i+k)%n] = nums[i];}System.arraycopy(t, 0, nums, 0, n);}
}
4、除自身以外数组的乘积
https://leetcode.cn/problems/product-of-array-except-self/description/?envType=study-plan-v2&envId=top-100-liked
class Solution {public int[] productExceptSelf(int[] nums) {int n = nums.length;int[] ans = new int[n];ans[0] = 1;// 记录第i个数左边的数的总乘积for(int i = 1; i < n; i++){ans[i] = ans[i-1]*nums[i-1];}int r = 1; // 记录第i个数右边的数的总乘积for(int i = n-1; i >= 0; i--){ans[i] = ans[i]*r;r *= nums[i];}return ans;}

相关文章:

  • Anaconda Prompt 切换工作路径的方法
  • mac 本地 docker 部署 nacos
  • 多路由器通过RIP动态路由实现通讯(单臂路由)
  • 使用谷歌浏览器自带功能将网页转换为PDF文件
  • liunx中常用操作
  • 树莓派4b 连接USB无线网卡
  • Spark_SQL
  • 基于亚马逊云科技 Amazon Bedrock Tool Use 实现 Generative UI
  • 人工智能在运动医学中的最新应用方向探析
  • 安全协议分析概述
  • 空间注意力和通道注意力的区别
  • MYSQL之慢查询分析(Analysis of Slow MySQL Query)
  • Java实现希尔排序算法
  • 前端Javascript模块化 CommonJS与ES Module区别
  • TS中的泛型
  • 适配器模式:化解接口不兼容的桥梁设计
  • Timm 加载本地 huggingface 模型
  • PostgreSQL 用户资源管理
  • 【软考】论NoSQL数据库技术及其应用示例
  • Session与Cookie的核心机制、用法及区别
  • 俄乌就不打击民用基础设施释放对话信号
  • 一条水脉串起七个特色区块,上海嘉定发布2025年新城行动方案
  • 曼谷没有“邻家男孩”:跨境追星族经历的“余震”
  • 罗马教皇方济各去世,享年88岁
  • 视觉周刊|第五届中国国际消费品博览会展现全球合作新格局
  • 伊朗外长: 下一轮伊美核问题谈判将于26日举行