1.二分查找(简单)(重要) 13
给定有序数组 找某个数的位置
//二分查找
public class BInarySort {
public static void main(String[] args) {
int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 , 11, 12, 13,14,15,16,17,18,19,20 };
int resIndex = binarySearch(arr, 0, arr.length - 1, 12);
System.out.println("resIndex=" + resIndex);
}
// 二分查找算法
public static int binarySearch(int[] arr, int left, int right, int findVal) {
// 当 left > right 时,说明递归整个数组,但是没有找到
if (left > right) {
return -1;
}
int mid = (left + right) >> 1;
int midVal = arr[mid];
if (findVal > midVal) { // 向右递归
return binarySearch(arr, mid + 1, right, findVal);
} else if (findVal < midVal) { // 向左递归
return binarySearch(arr, left, mid - 1, findVal);
} else {
return mid;
}
}
}
2.栈相关的题目
2.1.有效的括号(简单)(重要 ) 2
给定一个只包括 ‘(’,’)’,’{’,’}’,’[’,’]’ 的字符串,判断字符串是否有效。
有效字符串需满足:
左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
注意空字符串可被认为是有效字符串。
示例 1:
输入: “()”
输出: true
示例 2:
输入: “()[]{}”
输出: true
示例 3:
输入: “(]”
输出: false
示例 4:
输入: “([)]”
输出: false
示例 5:
输入: “{[]}”
输出: true
数据结构选择:
1)选择map保存括号之间的对应关系:使用到put,get,containsKey
2)选择stack来匹配对应关系:使用到push,pop,peek,empty方法
class Solution {
public boolean isValid(String s) {
if(s.length()%2!=0) return false;
if(s.equals("")) return true;
Map<Character,Character> map = new HashMap<Character,Character>();
map.put('(',')');
map.put('{','}');
map.put('[',']');
Stack<Character> stack = new Stack<Character>();
for(int i=0;i<s.length();i++) {
char c=s.charAt(i);
if(map.containsKey(c)){
stack.push(c);
} else {
if(!stack.empty()&&map.get(stack.peek())==c)
stack.pop();
else
return false;
}
}
return stack.empty();
}
}
2.2.最小栈(简单) 3
在实现栈的基本功能的基础上,再实现返回栈中最小元素的操作。
【要求】
1.pop、push、getMin操作的时间复杂度都是O(1)。
2.设计的栈类型可以使用现成的栈结构
思考:如果只用一个栈,那么getMin的操作时间复杂为O(n),因为获取最小值需要遍历。
设计思路:同时维护两个栈结构(系统提供的栈),一个栈就是正常的栈,另一个栈放当前的最小值,和第一个栈同步操作。
data栈正常存数据,min栈每次存的时候跟当前栈顶的数比较一下;当前数小于栈顶的数,则放入当前数,否则栈顶的数再存一次。
public static class MyStack {
private Stack<Integer> stackData;
private Stack<Integer> stackMin;
public MyStack() {
this.stackData = new Stack<Integer>();
this.stackMin = new Stack<Integer>();
}
public void push(int newNum) {
if (this.stackMin.isEmpty()) {
this.stackMin.push(newNum);
} else if (newNum < this.getmin()) {
this.stackMin.push(newNum);
} else {
int newMin = this.stackMin.peek();
this.stackMin.push(newMin);
}
this.stackData.push(newNum);
}
public int pop() {
if (this.stackData.isEmpty()) {
throw new RuntimeException("Your stack is empty.");
}
this.stackMin.pop();
return this.stackData.pop();//返回栈顶并弹出
}
public int getmin() {
if (this.stackMin.isEmpty()) {
throw new RuntimeException("Your stack is empty.");
}
return this.stackMin.peek();//peek就是返回栈顶不弹出
}
}
2.3.用栈实现队列(简单)
//用数组实现栈
public class ArrayStack {
private int maxSize; // 栈的大小
private int[] stack; // 数组,数组模拟栈,数据就放在该数组
private int top = -1;// top表示栈顶,初始化为-1
//构造器
public ArrayStack(int maxSize) {
this.maxSize = maxSize;
stack = new int[this.maxSize];
}
//栈满
public boolean isFull() {
return top == maxSize - 1;
}
//栈空
public boolean isEmpty() {
return top == -1;
}
//入栈-push
public void push(int value) {
if(isFull()) {
System.out.println("栈满");
return;
}
top++;
stack[top] = value;
}
//出栈-pop, 将栈顶的数据返回
public int pop() {
if(isEmpty()) {
throw new RuntimeException("栈空,没有数据~");
}
int value = stack[top];
top--;
return value;
}
//显示栈的情况[遍历栈], 遍历时,需要从栈顶开始显示数据
public void list() {
if(isEmpty()) {
System.out.println("栈空,没有数据~~");
return;
}
//需要从栈顶开始显示数据
for(int i = top; i >= 0 ; i--) {
System.out.printf("stack[%d]=%d\n", i, stack[i]);
}
}
}
3.链表
3.1.反转链表(简单)(重要) 52
方法一:迭代
假设链表为 1 \rightarrow 2 \rightarrow 3 \rightarrow \varnothing1→2→3→∅,我们想要把它改成 \varnothing \leftarrow 1 \leftarrow 2 \leftarrow 3∅←1←2←3。
在遍历链表时,将当前节点的 \textit{next}next 指针改为指向前一个节点。由于节点没有引用其前一个节点,因此必须事先存储其前一个节点。在更改引用之前,还需要存储后一个节点。最后返回新的头引用。
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;
}
}
3.2.环形链表(简单) 4
方法一:哈希表
思路及算法
最容易想到的方法是遍历所有节点,每次遍历到一个节点时,判断该节点此前是否被访问过。
具体地,我们可以使用哈希表来存储所有已经访问过的节点。每次我们到达一个节点,如果该节点已经存在于哈希表中,则说明该链表是环形链表,否则就将该节点加入哈希表中。重复这一过程,直到我们遍历完整个链表即可
public class Solution {
public boolean hasCycle(ListNode head) {
Set<ListNode> seen = new HashSet<ListNode>();
while (head != null) {
if (!seen.add(head)) {
return true;
}
head = head.next;
}
return false;
}
}
3.3.相交链表(简单) 7
方法一:哈希集合
思路和算法
判断两个链表是否相交,可以使用哈希集合存储链表节点。
首先遍历链表 \textit{headA}headA,并将链表 \textit{headA}headA 中的每个节点加入哈希集合中。然后遍历链表 \textit{headB}headB,对于遍历到的每个节点,判断该节点是否在哈希集合中:
如果当前节点不在哈希集合中,则继续遍历下一个节点;
如果当前节点在哈希集合中,则后面的节点都在哈希集合中,即从当前节点开始的所有节点都在两个链表的相交部分,因此在链表 \textit{headB}headB 中遍历到的第一个在哈希集合中的节点就是两个链表相交的节点,返回该节点。
如果链表 \textit{headB}headB 中的所有节点都不在哈希集合中,则两个链表不相交,返回 \text{null}null
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
Set<ListNode> visited = new HashSet<ListNode>();
ListNode temp = headA;
while (temp != null) {
visited.add(temp);
temp = temp.next;
}
temp = headB;
while (temp != null) {
if (visited.contains(temp)) {
return temp;
}
temp = temp.next;
}
return null;
}
}
3.4.重排链表(中等) 2
3.5.合并两个有序链表(简单) 3 。。。。
3.6.单链表有效节点的数据(简单) 新浪
头节点不统计
3.7.查找单链表倒数第k个节点(简单) 新浪
方法一:顺序查找
思路与算法
最简单直接的方法即为顺序查找,假设当前链表的长度为 nn,则我们知道链表的倒数第 kk 个节点即为正数第 n - kn−k 个节点,此时我们只需要顺序遍历到链表的第 n - kn−k 个节点即为倒数第 kk 个节点。
我们首先求出链表的长度 nn,然后顺序遍历到链表的第 n - kn−k 个节点返回即可
class Solution {
public ListNode getKthFromEnd(ListNode head, int k) {
int n = 0;
ListNode node = null;
for (node = head; node != null; node = node.next) {
n++;
}
for (node = head; n > k; n--) {
node = node.next;
}
return node;
}
}