都是基础题
1、反转链表
- 最直观的做法就是建立一个stack,倒进去再倒出来,不用想。
import java.util.*;
/**
* 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 reverseList(ListNode head) {
if(head==null){return null;}
Stack<Integer> stack = new Stack<>();
while(head!=null){
stack.push(head.val);
head = head.next;
}
head = new ListNode(); //复用了一下head 新建一个也没区别
ListNode newlistnode = head;
while(!stack.empty()){
head.val = stack.pop();
if(!stack.empty()) {
head.next = new ListNode();
head = head.next;
}
}
return newlistnode;
}
}
- 不用申请额外空间的方法:用指针倒来倒去,拿张纸画一下比较好想明白。思路就是断开链表的连接、指针反过来,就这样一路这样顺下去。
class Solution {
public ListNode reverseList(ListNode head) {
ListNode prev = null;
ListNode curr = head;
while (curr != null) {
ListNode next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
}
return prev;
}
}
作者:LeetCode-Solution
- 第三种就是递归,为什么要用递归呢?既不省资源又不好理解… 想学的时候再去leetcode上看题解吧。
2、数组中的第K个最大元素
题意:从小到大排好序后,返回倒数第K个元素。
- 懒人做法:
import java.util.Arrays;
class Solution {
public int findKthLargest(int[] nums, int k) {
int l = nums.length;
Arrays.sort(nums);
return nums[l-k];
}
}
真香 不用动脑子 但是如果面试时候这么写了 那要知道jvm里的sort是怎么运行的 不然写了个寂寞...
- 优化:和快排相关,因为快排的步骤是把整个数列分成大于和小于某个数左右两部分,这道题求第K大的数,因此只要保证右边的所有数都比他大就行,可通过简化快排算法来实现。
先写个快排复习复习
在这里插入代码片
再写个题解
在这里插入代码片
3、无重复的最长字串
题目描述:给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。
示例 1:
输入: s = “abcabcbb”
输出: 3
解释: 因为无重复字符的最长子串是 “abc”,所以其长度为 3。
示例 2:
输入: s = “bbbbb”
输出: 1
解释: 因为无重复字符的最长子串是 “b”,所以其长度为 1。
示例 3:
输入: s = “pwwkew”
输出: 3
解释: 因为无重复字符的最长子串是 “wke”,所以其长度为 3。
请注意,你的答案必须是 子串 的长度,“pwke” 是一个子序列,不是子串。
示例 4:
输入: s = “”
输出: 0
- 滑动窗口来解
- 第一次做不会做,看了别人的答案,使用hashset,优点就是每次的查询快。
class Solution {
public int lengthOfLongestSubstring(String s) {
if(s.length() == 0) return 0;
int left_point = -1, n = s.length();
int right_point = 0, max = 0;
HashSet set = new HashSet<Character>();
for(int i=0; i<n; i++){
if(left_point>=0) set.remove(s.charAt(left_point));
while(right_point<n && !set.contains(s.charAt(right_point))){ //右指针没有越界并且不重复
set.add(s.charAt(right_point));
max = (max>set.size()) ? max:set.size();
right_point++;
}
//右指针动完换左指针动
left_point++;
}
return max;
}
}
- 时隔两月再做这道题时 忘了自己做过了 直接用系统函数 代码简单 好理解 但效率不如hashset
class Solution {
public int lengthOfLongestSubstring(String s) {
if(s.length()<=1){return s.length();}
int max = 0;//记录窗口最大的大小
int i = 0,j = 0; //窗口初始大小为1
while(j<s.length()-1){
if(s.substring(i,j+1).contains(s.substring(j+1,j+2))){
//substring(begin,end)为[)左闭右开区间
//如果新的字符在窗口中有重复的 窗左边界右移 再进入循环判断
i++;
continue;
}else{//如果新的字符没有在窗口中 窗口右边界移动
j++;
}
max = (j-i+1>max)? j-i+1:max;
}
return max;
}
}