LC206.反转链表
存在递归和迭代的两种算法
迭代以及递归思路;
//迭代
class Solution {
public ListNode reverseList(ListNode head) {
ListNode pre = null,cur = head;
while(cur != null){
ListNode tmp = cur.next;
cur.next = pre;
pre = cur;
cur = tmp;
}
return pre;
}
}
//递归
class Solution {
public ListNode reverseList(ListNode head) {
if(head == null || head.next == null)
return head;
ListNode cur = reverseList(head.next);
head.next.next = head;
head.next = null;
return cur;
}
}
LC146.LRU缓存机制
核心思想在于:双向链表,位于链尾的可能是即将要被刷新的值,哈希表提高检索效率。
public class LRUCache {
//双向链表和hashmap
class ListNode{
private int key;
private int value;
private ListNode prev;
private ListNode next;
public ListNode(){}
public ListNode(int key,int value){
this.key = key;
this.value = value;
}
}
private HashMap<Integer,ListNode> cache = new HashMap();
private int capacity;
private int size;
private ListNode head,tail;
public LRUCache(int capacity){
this.size = 0;
this.capacity = capacity;
head = new ListNode();
tail = new ListNode();
head.next = tail;
tail.prev = head;
}
public int get(int key){
ListNode node = cache.get(key);
if(node == null)
return -1;
moveToHead(node);
return node.value;
}
public void put(int key,int value){
ListNode node = cache.get(key);
if(node == null){
//还有容量的时候
ListNode newnode = new ListNode(key,value);
cache.put(key,newnode);
addToHead(newnode);
++size;
if(size > capacity){
//删除cache对应的尾巴的值和双向链表尾巴的
ListNode tail = removeTail();
cache.remove(tail.key);
--size;
}
}else{
node.value = value;
moveToHead(node);
}
}
public void moveToHead(ListNode node){
removeNode(node);
addToHead(node);
}
public void removeNode(ListNode node){
node.prev.next = node.next;
node.next.prev = node.prev;
}
public void addToHead(ListNode node){
node.next = head.next;
node.prev = head;
head.next.prev = node;
head.next = node;
}
public ListNode removeTail(){
//先获取值然后删除尾巴.
ListNode res = tail.prev;
removeNode(res);
return res;
}
}
/**
* Your LRUCache object will be instantiated and called as such:
* LRUCache obj = new LRUCache(capacity);
* int param_1 = obj.get(key);
* obj.put(key,value);
*/
LC3.无重复字符的最长子串
关键在于滑动窗口的思想,什么时候扩大窗口需要做什么条件是什么,什么时候需要缩小窗口条件是什么并且做什么。
class Solution {
public int lengthOfLongestSubstring(String s) {
HashMap<Character,Integer> window = new HashMap();
int left = 0,right = 0;
int res = 0;
char[] strarr = s.toCharArray();
while(right < s.length()){
char c = strarr[right];
right++;
window.put(c,window.getOrDefault(c,0) + 1);
while(window.get(c) > 1){
char d = strarr[left];
left++;
window.put(d,window.getOrDefault(d,0) - 1);
}
res = Math.max(res,right - left);
}
return res;
}
}