力扣热题100
1. 两数字和
题目描述
- 自己第一版代码
class Solution {
// HashMap 缓存存储的是 key 是 数组中的值,value 存储的是 对应的下标
HashMap<Integer,Integer> map = new HashMap<>();
public int[] twoSum(int[] nums, int target) {
int L = nums.length;
for(int i = 0; i < L; i++) {
if(!map.containsKey(nums[i])){
map.put(nums[i],i);
}
}
for(int i = 0 ; i < L; i++){
if(map.containsKey(target - nums[i])){
if(map.get(target - nums[i]) != i){
return new int[] {
map.get(target - nums[i]),i};
}
}
}
return null;
}
}
- 第二版 使代码看起来更加简洁
class Solution {
HashMap<Integer,Integer> cache = new HashMap<>();
public int[] twoSum(int[] nums, int target) {
for(int i = 0; i < nums.length; i++){
// 如果在for循环中直接判断答案就不会出现同一个位置的答案
if(cache.containsKey(target - nums[i])){
return new int[] {
cache.get(target - nums[i]),i};
}
cache.put(nums[i],i);
}
return null;
}
}
2. 两数相加
题目描述:
解题思路:因为链表本身就是逆序的 所以可以直接进行相加 主要考虑的问题就是进位的问题 新一轮的计算也要考虑到进位的值
编码遇到的问题:自己没有想到如何处理null指针问题 -> 解决办法直接将节点Node 的 value的值提取出来(就是根据节点是不是null进行判断即可)
/**
* Definition for singly-linked list.
* public 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 Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
// 题目要求本身就是逆序的 所以可以直接相加
int value = 0; // 当前位置应该得到的值
int carry = 0; // 得到进位的值 下一次计算也应该考虑进去
ListNode dummy = new ListNode(); // 一般处理链表的问题都是需要用一个哨兵节点返回(dummy.next)
ListNode cur = dummy; // cur 节点 类似于 index索引
while(l1 != null || l2 != null || carry != 0){
// 确定value 和 carry 的值
// 真 TM 笨 直接把val的值提取出来就行了
int val1 = l1 == null ? 0 : l1.val;
int val2 = l2 == null ? 0 : l2.val;
value = (val1 + val2 + carry) % 10;
carry = (val1 + val2 + carry) / 10;
cur.next = new ListNode(value);
cur = cur.next;
l1 = l1 == null ? null : l1.next;
l2 = l2 == null ? null : l2.next;
}
return dummy.next;
}
}
3.无重复字符的最长字串
字串:要求连续 子序列:并不要求连续
题目要求:
解题思路:因为要求的是字串 所以可以联想到滑动窗口
- 一种使用set集合,set集合的长度就是字串的长度,使用set的长度于ans相比,查看是否需要更新答案
class Solution{
public int lengthOfLongestSubstring(String s){
if(s == null || s.length() == 0){
// 说明这是不合理的数据 直接返回ans = 0
return 0;
}
// 建立Set
HashSet<Character> set = new HashSet<>();
// 初始化两个辅助变量
int i = 0, start = 0; // i用来遍历s字符串 start用于更新滑动窗口的左边界
int ans = 0; // 我们要返回的答案
while(i < s.length()){
if(set.contains(s.charAt(i))){
// 说明集合中包含该元素,直接从前面开始移除
set.remove(s.charAt(start++));
}else{
// 说明集合中并没有这个字符 添加进set集合
set.add(s.charAt(i++));
}
// ans 每一轮都要进行更新
ans = Math.max(ans,set.size());
}
return ans;
}
}
- 使用map集合存储每个值最早出现的位置,还维护一个左边界
class Solution{
public int lengthOfLongestSubstring(String s){
// 建立hashMap map中的键值对 key 存储的是对应的字符 value对用的是该字符的下一个位置
HashMap<Character,Integer> map = new HashMap<>();
int left = 0; // 滑动窗口的左边界
int ans = 0;
for(int i = 0 ; i < s.length(); i++){
if(map.containsKey(s.charAt(i))){
// map中包含有该字符那么 滑动窗口的左边界有可能要进行更新
left = Math.max(left,map.get(s.charAt(i)));
}
// 即使当前字符已经出现在map集合里面 字符对应的出现的位置也要进行更新
map.put(s.charAt(i),i + 1); // 这里就可以表明map存储的值
ans = Math.max