- 二维数组中的查找
-
public class Solution {
public boolean Find(int target, int [][] array) {
boolean flag = false;
int row = 0;
if (array == null || array.length == 0 || array[0].length == 0) {
return flag;
}
int rows = array.length-1;
int columns = array[0].length-1;
// 注意判断条件
while (row>=0 && row<=rows && columns>=0 && columns<=array[0].length-1) {
if (array[row][columns]==target) {
flag = true;
System.out.println(array[row][columns]);
break;
} else {
// 从右上角开始查找
if (array[row][columns]>target)
// 比target值大,则列减一
columns = columns - 1;
else
// 比target值小,则行加一
row = row + 1;
}
}
return flag;
}
}
- 替换空格
-
public class Solution {
public String replaceSpace(StringBuffer str) {
if (str.equals(null) || str.length()<=0) {
return "";
}
String string = new String();
string = str.toString();
int count = 0;
int originLen = str.length();
// StringBuffer判断字符用法
for (int i=0;i<originLen;i++) {
if (str.charAt(i)==' ') {
count++;
}
}
// 扩充StringBuffer长度
int newchLen = str.length() + count*2;
// StringBuffer扩展长度用法
str.setLength(newchLen);
// 长度为 newchLen, 索引最大调用为 newchLen - 1
newchLen = newchLen - 1;
for (int j=originLen-1;j>=0;j--) {
if (str.charAt(j)==' ') {
// setCharAt 设置
str.setCharAt(newchLen--, '0');
str.setCharAt(newchLen--, '2');
str.setCharAt(newchLen--, '%');
} else {
str.setCharAt(newchLen--, str.charAt(j));
}
}
return str.toString();
}
}
- 从尾到头打印链表
-
/**
* public class ListNode {
* int val;
* ListNode next = null;
*
* ListNode(int val) {
* this.val = val;
* }
* }
*
*/
import java.util.Stack;
import java.util.ArrayList;
public class Solution {
public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
// 建立一个栈,把链表存进去,先进后出
Stack<Integer> stack = new Stack<Integer>();
while (listNode!=null) {
stack.push(listNode.val);
listNode = listNode.next;
}
// 建立一个链表,从栈里把元素一个一个取出来
ArrayList<Integer> list = new ArrayList<Integer>();
while (!stack.isEmpty()) {
list.add(stack.pop());
}
return list;
}
}
- 重建二叉树
-
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode reConstructBinaryTree(int [] preArr,int [] inArr) {
if (preArr == null || inArr == null) {
return null;
}
TreeNode root = reConstruce(preArr, 0, preArr.length-1, inArr, 0, inArr.length-1);
return root;
}
public TreeNode reConstruce(int[] preArr, int preS, int preE, int[] inArr, int inS, int inE) {
if (preS>preE || inS>inE) {
return null;
}
TreeNode root = new TreeNode(preArr[preS]);
for (int i=inS; i<=inE; i++) {
if (inArr[i]==preArr[preS]) {
// 记录 len,用于递归时确定 前序遍历序列的截取长度
int len = i - inS;
// preS+1 除去根结点
// 以i为中间递归左右子树
// 注意序列索引起止
root.left = reConstruce(preArr, preS+1, preS+len, inArr, inS, i-1);
root.right = reConstruce(preArr, preS+len+1, preE, inArr, i+1, inE);
}
}
System.out.print(root.val+" ");
return root;
}
}
- 用两个栈实现队列
-
import java.util.Stack;
public class Solution {
Stack<Integer> stack1 = new Stack<Integer>();
Stack<Integer> stack2 = new Stack<Integer>();
public void push(int node) {
stack1.push(node);
}
public int pop() {
if (stack1.size()<=0 && stack2.size()<=0) {
throw new RuntimeException("Queue is empty!");
}
if (stack2.size()!=0) {
return stack2.pop();
} else {
while (stack1.size()>0) {
stack2.push(stack1.pop());
}
return stack2.pop();
}
}
}
- 旋转数组的最小数字
-
import java.util.ArrayList;
public class Solution {
public int minNumberInRotateArray(int [] array) {
int left = 0;
int right = array.length-1;
if ( left > right || array == null) {
return -1;
}
int mid = 0;
while (left<right) {
// 取中间点
mid = (left+right)/2;
//特殊情况处理
if (array[mid]==array[left]&&array[mid]==array[right]) {
return array[right];
}
//左右相邻时,输出右边的值即最小值。
if (right-left==1)
return array[right];
//左边递增序列,右边递增序列判断。
if (array[mid]>=array[left]) {
left=mid;
} else {
right=mid;
}
}
return array[right];
}
}
- 斐波那契数列
-
public class Solution {
public int Fibonacci(int n) {
int f_1 = 1;
int f_2 = 0;
if (n == 0)
return f_2;
else if (n == 1)
return f_1;
else
return Fibonacci(n-1)+Fibonacci(n-2);
}
}
- 跳台阶
-
public class Solution {
public int JumpFloor(int target) {
int f_2 = 1;
int f_1 = 2;
int f_n = 0;
if (target == 1)
return f_2;
else if (target == 2)
return f_1;
else {
for (int i=3; i<=target; i++) {
f_n = f_1 + f_2;
f_2 = f_1;
f_1 = f_n;
}
return f_n;
}
}
}
- 变态跳台阶
-
public class Solution {
public int JumpFloorII(int target) {
if (target < 0)
return -1;
else if (target == 1)
return 1;
else
return 2*JumpFloorII(target-1);
}
}
- 矩形覆盖
-
public class Solution {
public int RectCover(int target) {
if (target <= 0)
return 0;
else if (target == 1)
return 1;
else if (target == 2)
return 2;
else
return RectCover(target-1)+RectCover(target-2);
}
}
- 二进制中1的个数
-
public class Solution {
public int NumberOf1(int n) {
int count = 0;
int flag = 1;
while (flag!=0) {
if ((n & flag)!=0)
count = count + 1;
flag = flag << 1;
}
return count;
}
}
- 数值的整数次方
-
public class Solution {
public double Power(double base, int exponent) {
double result = 0.0;
if (base == 0 && exponent == 0)
return -1;
if (exponent<0) {
result = PowerWithUnsignedExponent(base,-exponent);
result = 1.0/result;
} else {
result = PowerWithUnsignedExponent(base,exponent);
}
return result;
}
public double PowerWithUnsignedExponent(double base, int exponent) {
// 注意 double
double result = 1.0;
for (int i=1;i<=exponent;i++)
// 连乘
result = base*result;
return result;
}
}
- 调整数组顺序使奇数位于偶数前面
-
public class Solution {
public void reOrderArray(int [] array) {
// 边界判断
if (array.length < 1)
return;
for (int i=0; i< array.length; i++) {
if ( (array[i]&1)==1 ) {
int temp = array[i];
int j=i-1;
while (j>=0 && (array[j]&1)==0) {
array[j+1] = array[j];
j--;
}
array[j+1]= temp;
}
}
}
// 函数判断是否n是偶数
public boolean isEven(int n) {
Boolean flag = false;
if ((n & 1) == 0)
flag = true;
return flag;
}
public static void printArray(int[] array) {
for (int i=0; i< array.length; i++)
System.out.print(array[i]);
}
}
- 链表中倒数第k个结点
-
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
public class Solution {
public ListNode FindKthToTail(ListNode head,int k) {
// 边界判断
if (k < 1 || head == null)
return null;
ListNode headFirst = head;
// k 判断
for (int i=1; i<k; i++) {
if (headFirst.next!=null)
headFirst = headFirst.next;
else
return null;
}
// 倒数第k个,即n-k+1个,不知道n的情况下,可以设置两个指针
// 第一个先走到 k-1处,第二个再走,这样的话当第一个走到结尾时,即n,第一个和第二个相差 k-1个
// 即第二个在 n-k+1处
while (headFirst.next!=null) {
headFirst = headFirst.next;
head = head.next;
}
return head;
}
}
- 反转链表
-
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
public class Solution {
public ListNode ReverseList(ListNode head) {
if (head == null) {
return null;
}
// 定义三个节点,用于链表反转
ListNode pReverseHead = null;
ListNode pNode = head;
ListNode pPreNode = null;
ListNode pNext = null;
while (pNode != null) {
pNext = pNode.next;
if (pNode.next == null)
pReverseHead = pNode;
// 链表指向箭头反转
pNode.next = pPreNode;
// 链表移动
pPreNode = pNode;
pNode = pNext;
}
return pReverseHead;
}
}
- 合并两个排序的链表
-
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
public class Solution {
public ListNode Merge(ListNode list1,ListNode list2) {
if (list1 == null)
return list2;
else if (list2 == null)
return list1;
// 定义合并链表
ListNode ListMerge = null;
if (list1.val < list2.val) {
ListMerge = list1;
ListMerge.next = Merge(list1.next, list2);
} else {
ListMerge = list2;
ListMerge.next = Merge(list1, list2.next);
}
return ListMerge;
}
}
- 树的子结构
-
/**
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
public boolean HasSubtree(TreeNode root1,TreeNode root2) {
boolean result = false;
if (root1 == null)
return false;
if (root2 == null)
return false;
if (root1 != null && root2 != null) {
if (root1.val == root2.val)
result = DoesTree1HaveTree2(root1, root2);
if (!result)
result = HasSubtree(root1.left, root2);
if (!result)
result = HasSubtree(root1.right, root2);
return result;
}
return false;
}
public static boolean DoesTree1HaveTree2(TreeNode root1,TreeNode root2) {
if (root2 == null)
return true;
if (root1 == null)
return false;
if (root1.val != root2.val)
return false;
return DoesTree1HaveTree2(root1.left,root2.left)&&DoesTree1HaveTree2(root1.right,root2.right);
}
}
- 二叉树的镜像
-
/**
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
public void Mirror(TreeNode root) {
if (root != null) {
TreeNode tempNode = root.left;
root.left = root.right;
root.right = tempNode;
if (root.left != null)
Mirror(root.left);
if (root.right != null)
Mirror(root.right);
}
}
}
- 顺时针打印矩阵
-
import java.util.ArrayList;
public class Solution {
ArrayList<Integer> list = new ArrayList<>();
public ArrayList<Integer> printMatrix(int [][] matrix) {
if (matrix == null || matrix.length<=0 || matrix[0].length<=0)
return null;
int start = 0;
int rows = matrix.length;
int columns = matrix[0].length;
while (columns > start*2 && rows > start*2) {
PrintMatrixInCircle(matrix, columns, rows, start);
start++;
}
return list;
}
public void PrintMatrixInCircle(int [][] matrix, int columns, int rows, int start) {
// 终止列
int endX = columns - 1 - start;
// 终止行
int endY = rows -1 - start;
// 从左到右
for (int i = start; i <= endX; i++) {
// 行不变(初始行start),列递增
list.add(matrix[start][i]);
System.out.print(matrix[start][i] + " ");
}
// 从下到上
for (int i = start+1; i <= endY; i++) {
// 行递增,列不变(终止列 endX)
list.add(matrix[i][endX]);
System.out.print(matrix[i][endX] + " ");
}
// 从右往左
// 至少要有两行两列
if ( start < endX && start < endY) {
for (int i = endX - 1; i >= start; i--) {
// 行不变(终止行endY),列递减
list.add(matrix[endY][i]);
System.out.print(matrix[endY][i] + " ");
}
}
// 从下往上
// 至少要有三行两列
if (start < endX && start < endY - 1) {
for (int i = endY - 1; i >= start + 1; i--) {
// 行递减,列不变(初始列start)
list.add(matrix[i][start]);
System.out.print(matrix[i][start] + " ");
}
}
}
}
- 包含min函数的栈
-
import java.util.Stack;
public class Solution {
Stack<Integer> dataStack = new Stack<Integer>();
Stack<Integer> minStack = new Stack<Integer>();
public void push(int node) {
// dataStack 直接放入数值
dataStack.push(node);
// 如果node比Min值小, 则放入当前 node值;否则,放入Min值
if (minStack.isEmpty() || node < minStack.peek()) {
minStack.push(node);
} else {
minStack.push(minStack.peek());
}
}
public void pop() {
// 同时取出
dataStack.pop();
minStack.pop();
}
public int top() {
return dataStack.peek();
}
public int min() {
return minStack.peek();
}
}
- 栈的压入、弹出序列
-
import java.util.ArrayList;
import java.util.Stack;
public class Solution {
public boolean IsPopOrder(int [] pushA,int [] popA) {
if (pushA == null || popA == null || pushA.length < 0 || popA.length < 0)
return false;
// 设置初始位,用于pop移动
int pos = 0;
Stack<Integer> s = new Stack<Integer>();
for (int i = 0; i<pushA.length; i++) {
s.push(pushA[i]);
// 如果栈非空,并且栈顶的数等于取出来的数
while (!s.isEmpty() && s.peek() == popA[pos]) {
s.pop();
pos ++ ;
}
}
return s.empty();
}
}
- 从上往下打印二叉树
-
import java.util.ArrayList;
/**
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
public ArrayList<Integer> PrintFromTopToBottom(TreeNode root) {
// 列表
ArrayList<Integer> list = new ArrayList<>();
// 队列
ArrayList<TreeNode> queue = new ArrayList<>();
if (root == null)
return list;
// 先进
queue.add(root);
while (queue.size()!=0) {
// 先出
TreeNode temp = queue.remove(0);
// 找左右节点
if (temp.left!=null)
queue.add(temp.left);
if (temp.right!=null)
queue.add(temp.right);
// 将值添加到list
list.add(temp.val);
}
return list;
}
}
- 二叉搜索树的后序遍历序列
-
public class Solution {
public static boolean VerifySquenceOfBST(int [] sequence) {
if (sequence.length <= 0 || sequence == null) {
return false;
}
return VerifySquenceOfBST(sequence, 0, sequence.length - 1);
}
public static boolean VerifySquenceOfBST(int[] sequence, int start, int end) {
// 如果对应要处理的数据只有一个或者已经没有数据要处理(start>end)就返回true
if (start >= end) {
return true;
}
// 找到root节点
int root = sequence[end];
// 左子树和右子树的分割点
int index = start;
for (; index< end-1; index++) {
// 左子树找是否有大于根节点的值
if (sequence[index]>root)
break;
}
int right = index;
for (; index<end-1; index++) {
// 右子树找是否有小于根节点的根
if (sequence[index]<root)
break;
}
if (index!=end-1)
return false;
index = right;
// 递归查找该数组是不是某二叉搜索树的后序遍历结果
return VerifySquenceOfBST(sequence, start, index-1)&&VerifySquenceOfBST(sequence, index, end-1);
}
}
- 二叉树中和为某一值的路径
-
import java.util.ArrayList;
/**
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
public static ArrayList<ArrayList<Integer>> FindPath(TreeNode root,int target) {
ArrayList<ArrayList<Integer>> listAll = new ArrayList<ArrayList<Integer>>();
if (root == null) {
return listAll;
} else {
return FindPath(listAll, root, 0, target, new ArrayList<Integer>());
}
}
public static ArrayList<ArrayList<Integer>> FindPath(ArrayList<ArrayList<Integer>> listAll, TreeNode root, int curSum, int target, ArrayList<Integer> list) {
if (root != null) {
// 值累加
curSum += root.val;
// 将节点加入list
list.add(root.val);
// 如果curSum小于target,递归左右节点
if (curSum < target) {
FindPath(listAll, root.left, curSum, target, list);
FindPath(listAll, root.right, curSum, target, list);
}
// 如果curSum等于target,输出路径
else if (curSum == target && root.left == null && root.right == null) {
//注意:这里不能用 lists.add(list);
listAll.add(new ArrayList<Integer>(list));
}
// 其它情况,移除节点
list.remove(list.size()-1);
}
return listAll;
}
}
- 复杂链表的复制
-
/*
public class RandomListNode {
int label;
RandomListNode next = null;
RandomListNode random = null;
RandomListNode(int label) {
this.label = label;
}
}
*/
public class Solution {
public RandomListNode Clone(RandomListNode pHead) {
// 边界判断
if (pHead == null)
return null;
// 复制普通节点
RandomListNode pCur = pHead;
while (pCur!=null) {
// 复制节点的值
RandomListNode node = new RandomListNode(pCur.label);
node.next = pCur.next;
// 指向新复制出来的节点
pCur.next = node;
// 指向下一个原节点
pCur = node.next;
}
// 重置到头节点
pCur = pHead;
// 复制随机节点
while (pCur!=null) {
if (pCur.random!=null) {
// pCur.next即复制节点,复制节点的随机节点,即当前节点的随机节点的下一节点
pCur.next.random = pCur.random.next;
}
pCur = pCur.next.next;
}
// 拆分
// 定义复制链表的头节点。
RandomListNode head = pHead.next;
RandomListNode cur = head;
// 重置到头节点
pCur = pHead;
while (pCur!=null) {
pCur.next = pCur.next.next;
if (cur.next!=null) {
cur.next = cur.next.next;
}
// 前移
pCur = pCur.next;
cur = cur.next;
}
return head;
}
}
- 二叉搜索树与双向链表
-
/**
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
public static TreeNode Convert(TreeNode pRootOfTree) {
// 用于保存处理过程中的双向链表的尾节点
TreeNode[] endNode = new TreeNode[1];
Convert(pRootOfTree, endNode);
TreeNode headNode = endNode[0];
while (headNode!=null && headNode.left!=null) {
headNode = headNode.left;
}
return headNode;
}
public static void Convert(TreeNode pRootOfTree, TreeNode[] endNode) {
if (pRootOfTree == null)
return;
// 从根节点出发
TreeNode pNode = pRootOfTree;
if (pNode.left != null) {
Convert(pNode.left, endNode);
}
// 当前节点的前驱指向尾节点
pNode.left = endNode[0];
// 如果尾节点不为空
if (endNode[0]!=null) {
endNode[0].right = pNode;
}
// 当前节点为尾节点
endNode[0] = pNode;
// 遍历右子树
if (pNode.right != null) {
Convert(pNode.right, endNode);
}
}
}
- 字符串的排列
-
import java.util.ArrayList;
import java.util.Collections;
public class Solution {
public static ArrayList<String> Permutation(String str) {
ArrayList<String> list = new ArrayList<>();
char[] chars = str.toCharArray();
if (chars == null || chars.length <= 0) {
System.out.println("Error");
}
permutation(chars, 0, list);
// 字典顺序
Collections.sort(list);
System.out.print(list.toString());
return list;
}
public static void permutation(char[] chars, int begin, ArrayList<String> list) {
if (chars.length -1 == begin) {
//System.out.print(new String(chars)+" ");
list.add(new String(chars));
} else {
char tmp;
int i = begin;
for (; i<chars.length; i++) {
if (i!=begin && chars[i] == chars[begin])
continue;
tmp = chars[i];
chars[i] = chars[begin];
chars[begin] = tmp;
// 处理 begin+1
permutation(chars, begin+1, list);
// 对调后恢复
tmp = chars[i];
chars[i] = chars[begin];
chars[begin] = tmp;
}
}
}
}
- 数组中出现次数超过一半的数字
-
public class Solution {
public int MoreThanHalfNum_Solution(int [] array) {
if (array == null || array.length <= 0) {
return 0;
}
int result = array[0];
int times = 1;
for (int i=1; i<array.length; i++) {
if (times == 0) {
result = array[i];
times = 1;
} else if (result == array[i]) {
times++;
} else {
times--;
}
}
int count = 0;
for (int i=0; i<array.length; i++) {
if (result == array[i]) {
count++;
}
}
if (count > array.length/2) {
return result;
} else {
return 0;
}
}
}
- 最小的K个数
-
import java.util.ArrayList;
import java.util.Comparator;
import java.util.PriorityQueue;
public class Solution {
public ArrayList<Integer> GetLeastNumbers_Solution(int [] input, int k) {
ArrayList<Integer> list = new ArrayList<>();
if (input == null || input.length<=0 || k>input.length || k<=0)
return list;
PriorityQueue<Integer> maxHeap = new PriorityQueue<Integer>(k, new Comparator<Integer>(){
@Override
public int compare(Integer o1, Integer o2) {
// TODO Auto-generated method stub
return o2.compareTo(o1);
}
});
for (int i=0; i<input.length; i++) {
if (maxHeap.size()!=k) {
maxHeap.offer(input[i]);
} else if (maxHeap.peek()>input[i]) {
Integer tmp = maxHeap.poll();
tmp = null;
maxHeap.offer(input[i]);
}
}
for (Integer integer:maxHeap) {
list.add(integer);
}
return list;
}
}
- 连续子数组的最大和
-
public class Solution {
public int FindGreatestSumOfSubArray(int[] array) {
if (array == null || array.length <= 0)
return 0;
int nCurSum = 0;
int nMaxSum = 0x80000000;
for (int i=0; i< array.length; i++) {
if (nCurSum <= 0)
nCurSum = array[i];
else
nCurSum = nCurSum + array[i];
if (nCurSum > nMaxSum) {
nMaxSum = nCurSum;
}
}
return nMaxSum;
}
}
- 整数中1出现的次数(从1到n整数中1出现的次数)
-
public class Solution {
public int NumberOf1Between1AndN_Solution(int n) {
if (n < 0)
return 0;
int count = 0, weight = 0, round = n, base = 1;
while (round > 0) {
weight = round % 10;
round = round / 10;
count = count + round * base;
if (weight == 1)
count = count + (n % base) + 1;
else if (weight > 1)
count = count + base;
base = base * 10;
}
return count;
}
}
- 把数组排成最小的数
-
import java.util.Comparator;
import java.util.Arrays;
public class Solution {
public String PrintMinNumber(int [] numbers) {
if (numbers == null || numbers.length <= 0)
return "";
String[] str = new String[numbers.length];
StringBuffer sb = new StringBuffer();
for (int i = 0; i < numbers.length; i++) {
str[i] = String.valueOf(numbers[i]);
}
// 重写一下排序的方法
Arrays.sort(str, new Comparator<String>(){
@Override
public int compare(String s1, String s2) {
String str1 = s1 + s2;
String str2 = s2 + s1;
return str1.compareTo(str2);
}
});
for (int i = 0; i < numbers.length; i++) {
sb.append(str[i]);
}
return sb.toString();
}
}
- 丑数
-
public class Solution {
public static int GetUglyNumber_Solution(int index) {
if (index <= 0)
return 0;
int[] arrUglyNumber = new int[index];
arrUglyNumber[0] = 1;
int nextUglyNumber = 1;
int multiply2 = 0;
int multiply3 = 0;
int multiply5 = 0;
while (nextUglyNumber < index) {
int min = Min(arrUglyNumber[multiply2]*2, arrUglyNumber[multiply3]*3, arrUglyNumber[multiply5]*5);
arrUglyNumber[nextUglyNumber] = min;
while (arrUglyNumber[multiply2]*2 <= arrUglyNumber[nextUglyNumber]) {
multiply2++;
}
while (arrUglyNumber[multiply3]*3 <= arrUglyNumber[nextUglyNumber]) {
multiply3++;
}
while (arrUglyNumber[multiply5]*5 <= arrUglyNumber[nextUglyNumber]) {
multiply5++;
}
nextUglyNumber++;
}
return arrUglyNumber[nextUglyNumber - 1];
}
public static int Min(int int1, int int2, int int3) {
int tmp = (int1 <= int2)?int1:int2;
return (tmp <= int3)?tmp:int3;
}
}
- 第一个只出现一次的字符位置
-
import java.util.LinkedHashMap;
public class Solution {
public int FirstNotRepeatingChar(String str) {
if ( str == null || str.length() <= 0)
return -1;
LinkedHashMap<Character, Integer> map = new LinkedHashMap<>();
for (int i = 0; i < str.length(); i++) {
if (map.containsKey(str.charAt(i))) {
int time = map.get(str.charAt(i));
time++;
map.put(str.charAt(i), time);
} else {
map.put(str.charAt(i), 1);
}
}
int pos = -1;
for (int i = 0; i < str.length(); i++) {
if (map.get(str.charAt(i)) == 1)
return i;
}
return pos;
}
}
- 数组中的逆序对
-
public class Solution {
public static int InversePairs(int[] array) {
if (array == null || array.length <= 0)
return 0;
return (mergeSort(array, 0, array.length - 1));
}
public static int mergeSort(int[] array, int left, int right) {
if (left == right)
return 0;
int mid = (left + right)/2;
int leftNum = mergeSort(array, left, mid);
int rightNum = mergeSort(array, mid+1, right);
return (Sort(array, left, mid, right) + leftNum + rightNum)% 1000000007;
}
public static int Sort(int[] array, int left, int middle, int right) {
int len = right - left;
int middleVal = middle;
int rightVal = right;
int[] temp = new int[len+1];
int nums = 0;
while (middleVal >= left && rightVal >= middle+1) {
if (array[middleVal] > array[rightVal]) {
temp[len--] = array[middleVal--];
nums = nums + rightVal - (middle+1) + 1;
if (nums > 1000000007) {
nums %= 1000000007;
}
} else {
temp[len--] = array[rightVal--];
}
}
while (middleVal >= left)
temp[len--] = array[middleVal--];
while (rightVal >= middle+1)
temp[len--] = array[rightVal--];
int i = 0;
while (left <= right) {
array[left++] = temp[i++];
}
return nums;
}
}
- 两个链表的第一个公共结点
-
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
public class Solution {
public static ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
if (pHead1 == null || pHead2 == null)
return null;
int len1 = GetLength(pHead1);
int len2 = GetLength(pHead2);
ListNode pHeadLong = null;
ListNode pHeadShort = null;
int d = 0;
if (len1 > len2) {
pHeadLong = pHead1;
pHeadShort = pHead2;
d = len1 - len2;
} else {
pHeadLong = pHead2;
pHeadShort = pHead1;
d = len2 - len1;
}
for (int i = 0; i < d; i++) {
pHeadLong = pHeadLong.next;
}
while (pHeadLong != null && pHeadShort != null && pHeadLong != pHeadShort) {
pHeadLong = pHeadLong.next;
pHeadShort = pHeadShort.next;
}
return pHeadLong;
}
public static int GetLength(ListNode pHead) {
int len = 0;
if (pHead == null)
return 0;
while (pHead != null) {
len++;
pHead = pHead.next;
}
return len;
}
}
- 数字在排序数组中出现的次数
-
public class Solution {
public static int GetNumberOfK(int [] array , int k) {
if (array == null || array.length <= 0 || k < 0)
return 0;
int number = 0;
int start = 0, end = array.length - 1;
start = GetFirstK(array, start, end, k);
end = GetEndK(array, start, end, k);
if (start > -1 && end > -1) {
number = end - start + 1;
}
return number;
}
public static int GetFirstK(int[] array, int start, int end, int k) {
if (start > end)
return -1;
int mid = start + (end - start)/2;
if (mid < 0)
return -1;
if (mid - 1 >= 0 && array[mid] > k )
return GetFirstK(array, start, mid - 1, k);
else if (mid + 1 <= array.length - 1 && array[mid] < k)
return GetFirstK(array, mid + 1, end, k);
else if (mid - 1 >= 0 && array[mid - 1] == k)
return GetFirstK(array, start, mid - 1, k);
else {
if (array[mid] == k)
return mid;
else
return -1;
}
}
public static int GetEndK(int[] array, int start, int end, int k) {
if (start > end)
return -1;
int mid = start + (end - start)/2;
if (mid < 0)
return -1;
//System.out.println(mid);
if (mid - 1 >= 0 && array[mid] > k )
return GetEndK(array, start, mid - 1, k);
else if (mid + 1 <= array.length - 1 && array[mid] < k)
return GetEndK(array, mid + 1, end, k);
else if (mid + 1 <= array.length - 1 && mid + 1 >= 0 && array[mid + 1] == k)
return GetEndK(array, mid + 1, end, k);
else {
if (array[mid] == k)
return mid;
else
return -1;
}
}
}
- 二叉树的深度
-
/**
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
public int TreeDepth(TreeNode root) {
if (root == null)
return 0;
int nLeft = TreeDepth(root.left);
int nRight = TreeDepth(root.right);
return (nLeft > nRight)?(nLeft + 1):(nRight + 1);
}
}
- 平衡二叉树
-
public class Solution {
public boolean IsBalanced_Solution(TreeNode root) {
if (root == null)
return true;
int left = GetDepth(root.left);
int right = GetDepth(root.right);
if (Math.abs(left - right) > 1)
return false;
return (IsBalanced_Solution(root.left)&&IsBalanced_Solution(root.right));
}
public int GetDepth(TreeNode root) {
if (root == null)
return 0;
int leftN = GetDepth(root.left) + 1;
int rightN = GetDepth(root.right) + 1;
return (leftN > rightN)?leftN:rightN;
}
}
- 数组中只出现一次的数字
-
//num1,num2分别为长度为1的数组。传出参数
//将num1[0],num2[0]设置为返回结果
public class Solution {
public void FindNumsAppearOnce(int [] array,int num1[] , int num2[]) {
//public static int[] FindNumsAppearOnce(int[] array) {
// int[] result = {0, 0};
// if (array == null || array.length < 2)
// return result;
int xor = 0;
for (int i:array) {
xor^= i;
}
int indexOf1 = FindFirstBit1(xor);
for (int i:array) {
if (IsBit1(i,indexOf1)) {
num1[0]^=i;
} else {
num2[0]^=i;
}
}
}
private static int FindFirstBit1(int num) {
int indexBit = 0;
while ((num & 1) == 0 && (indexBit < 4*8)) {
num = num >> 1;
++ indexBit;
}
return indexBit;
}
private static boolean IsBit1(int num, int indexBit) {
num = num >> indexBit;
return (num & 1) == 1;
}
}
- 和为S的连续正数序列
-
import java.util.ArrayList;
public class Solution {
public ArrayList<ArrayList<Integer> > FindContinuousSequence(int sum) {
ArrayList<ArrayList<Integer>> listAll = new ArrayList<>();
if (sum < 3)
return listAll;
int start = 1;
int end = 2;
int mid = (1 + sum)/2;
int curSum = start + end;
while (start < mid) {
ArrayList<Integer> list = new ArrayList<>();
if (curSum == sum) {
for (int i = start; i <=end; i++)
list.add(i);
listAll.add(list);
}
while (curSum > sum && start < mid) {
curSum -=start;
start++;
if (curSum == sum) {
for (int i = start; i <=end; i++)
list.add(i);
listAll.add(list);
}
}
end++;
curSum +=end;
}
return listAll;
}
}
- 和为S的两个数字
-
import java.util.ArrayList;
public class Solution {
public ArrayList<Integer> FindNumbersWithSum(int [] array,int sum) {
ArrayList<Integer> list = new ArrayList<>();
if (array == null || array.length <= 0 )
return list;
int curSum = 0;
int start = 0;
int end = array.length - 1;
while (start < end) {
curSum = array[start] + array[end];
if (curSum == sum) {
list.add(array[start]);
list.add(array[end]);
break;
} else if (curSum > sum) {
end--;
} else {
start++;
}
}
return list;
}
}
- 左旋转字符串
-
public class Solution {
public static String LeftRotateString(String str,int n) {
if (str == null || str.length() < 1 || n < 0)
return str;
char[] strChar = str.toCharArray();
Reverse(strChar, 0, n - 1);
Reverse(strChar, n, strChar.length - 1);
Reverse(strChar, 0, strChar.length - 1);
return new String(strChar);
}
public static void Reverse(char[] strChar, int start, int end) {
while (start < end) {
char tmp = strChar[start];
strChar[start] = strChar[end];
strChar[end] = tmp;
start++;
end--;
}
}
}
- 翻转单词顺序列
-
public class Solution {
public String ReverseSentence(String str) {
if (str == null || str.length() < 1)
return str;
char[] strChar = str.toCharArray();
Reverse(strChar, 0, strChar.length-1);
int start = 0, end = 0;
while (start < strChar.length) {
if (strChar[start] == ' ') {
start++;
end++;
} else if (end == strChar.length || strChar[end] == ' ') {
Reverse(strChar, start, end-1);
end++;
start = end;
} else {
end++;
}
}
return new String(strChar);
}
public void Reverse(char[] strChar, int start, int end) {
while (start < end) {
char tmp = strChar[start];
strChar[start] = strChar[end];
strChar[end] = tmp;
start++;
end--;
}
}
}
- 扑克牌顺子
-
import java.util.Arrays;
public class Solution {
public boolean isContinuous(int [] numbers) {
if (numbers == null || numbers.length <= 0)
return false;
int spaceNumber = 0;
int gapNumber = 0;
Arrays.sort(numbers);
for (int i = 0; i < numbers.length; i++) {
if (numbers[i] == 0)
spaceNumber++;
}
int small = spaceNumber;
int big = small+1;
while (big < numbers.length) {
if (numbers[small] == numbers[big])
return false;
gapNumber += numbers[big] - numbers[small] - 1;
small = big;
big++;
}
if (spaceNumber >= gapNumber)
return true;
else
return false;
}
}
- 孩子们的游戏(圆圈中最后剩下的数)
-
import java.util.LinkedList;
public class Solution {
public int LastRemaining_Solution(int n, int m) {
if (n < 1 || m < 1)
return -1;
LinkedList<Integer> list = new LinkedList<>();
for (int i = 0; i < n; i++)
list.add(i);
int index = 0;
while (list.size()>1) {
// 移动m-1步到达m
for (int i = 1; i < m; i++) {
index = (index + 1)%list.size();
}
list.remove(index);
}
return list.get(0);
}
}
- 求1+2+3+...+n
-
public class Solution {
public int Sum_Solution(int n) {
int val = (int)(Math.pow(n,2)+n) >> 1;
return val;
}
}
- 不用加减乘除做加法
-
public class Solution {
public int Add(int num1,int num2) {
while (num2 != 0) {
int temp = num1^num2;
num2 = (num1&num2)<<1;
num1 = temp;
}
return num1;
}
}
- 把字符串转换成整数
-
public class Solution {
public static boolean flag;
public static int StrToInt(String str) {
if (str == null || str.length() < 1) {
flag = false;
return 0;
}
int[] strToIntArr = new int[str.length()];
char symbol =str.charAt(0);
boolean symbolFlag = true;
int start = 0;
if (symbol == '+') {
symbolFlag = true;
start = 1;
} else if (symbol == '-') {
symbolFlag = false;
start = 1;
}
int sum = 0;
for (int i = start; i < str.length(); i++) {
if (str.charAt(i) >= '0' && str.charAt(i)<='9')
sum = sum*10+str.charAt(i) - '0';
else {
flag = true;
return 0;
}
}
if (symbolFlag) {
if (sum >= 0x8000_0000L) {
flag = true;
return 0;
} else {
sum = (int)sum;
}
} else {
if (sum == 0x8000_0000L) {
sum = 0x8000_0000;
} else {
sum = (int)-sum;
}
}
if (sum == 0) {
flag = true;
}
return sum;
}
}
- 数组中重复的数字
-
public class Solution {
// Parameters:
// numbers: an array of integers
// length: the length of array numbers
// duplication: (Output) the duplicated number in the array number,length of duplication array is 1,so using duplication[0] = ? in implementation;
// Here duplication like pointor in C/C++, duplication[0] equal *duplication in C/C++
// 这里要特别注意~返回任意重复的一个,赋值duplication[0]
// Return value: true if the input is valid, and there are some duplications in the array number
// otherwise false
public boolean duplicate(int numbers[],int length,int [] duplication) {
if (numbers == null || length<=0)
return false;
int tempVal = 0;
for (int i=0;i<numbers.length;i++) {
while (numbers[i]!=i) {
if (numbers[i]==numbers[numbers[i]]) {
//System.out.println(numbers[i]);
duplication[0] = numbers[i];
return true;
}
tempVal = numbers[i];
numbers[i] = numbers[tempVal];
numbers[tempVal] = tempVal;
}
}
return false;
}
}
- 构建乘积数组
-
import java.util.ArrayList;
public class Solution {
public int[] multiply(int[] A) {
int len = A.length;
int[] left = new int[len];
int[] right = new int[len];
// 注意这行
left[0] = left[len-1] = right[0] = right[len-1]=1;
for (int i = 1; i < len; i++) {
left[i] = left[i-1]*A[i-1];
}
for (int i = len - 2; i>=0; i--) {
right[i] = right[i+1]*A[i+1];
}
int[] B = new int[len];
while (len > 0) {
len--;
B[len] = left[len]*right[len];
}
return B;
}
}
- 正则表达式匹配
-
public class Solution {
public boolean match(char[] str, char[] pattern) {
if (str == null || pattern == null || str.length<0 || pattern.length<0)
if (str == null || pattern == null )
return false;
// 递归调用
return matchCore(str, 0, pattern, 0 );
}
// strIndex和patternIndex是索引
public boolean matchCore(char[] str, int strIndex, char[] pattern, int patternIndex) {
System.out.println(strIndex);
// 都到达末尾, 取 str.length、pattern.length
if (strIndex == str.length && patternIndex == pattern.length)
return true;
// 只有模式串到达结尾,说明匹配失败
if (strIndex != str.length && patternIndex == pattern.length)
return false;
// 模式第2个是*,且字符串第1个跟模式第1个匹配,分3种匹配模式;如不匹配,模式后移2位
if (patternIndex + 1 < pattern.length && pattern[patternIndex+1] == '*') {
if ((strIndex!=str.length && str[strIndex]==pattern[patternIndex]) || (strIndex!=str.length && pattern[patternIndex] == '.')) {
return ((matchCore(str, strIndex, pattern, patternIndex+2)) ||
(matchCore(str, strIndex+1, pattern, patternIndex)) ||
(matchCore(str, strIndex+1, pattern, patternIndex+2)));
} else {
return matchCore(str, strIndex, pattern, patternIndex+2);
}
}
// 模式第2个不是*,且字符串第1个跟模式第1个匹配,则都后移1位,否则直接返回false
if ((strIndex!=str.length && str[strIndex]==pattern[patternIndex]) || (strIndex!=str.length && pattern[patternIndex] == '.')) {
return matchCore(str, strIndex+1, pattern, patternIndex+1);
}
return false;
}
}
- 表示数值的字符串
-
public class Solution {
private int index = 0;
public boolean isNumeric(char[] str) {
if (str.length < 1)
return false;
boolean flag = scanInteger(str);
if (index < str.length && str[index] == '.') {
index++;
flag = scanUnsignedInteger(str) || flag;
}
if (index < str.length && (str[index] == 'e' || str[index] == 'E')) {
index++;
flag = flag && scanInteger(str);
}
return flag && index == str.length;
}
public boolean scanInteger(char[] str) {
if (index < str.length && (str[index]=='+'||str[index]=='-')) {
index++;
}
return scanUnsignedInteger(str);
}
public boolean scanUnsignedInteger(char[] str) {
int temp = index;
while (index < str.length && (str[index]>='0'&& str[index]<='9')) {
index++;
}
return temp<index;
}
}
- 字符流中第一个不重复的字符
-
import java.util.LinkedHashMap;
import java.util.Map;
public class Solution {
LinkedHashMap<Character, Integer> map = new LinkedHashMap<>();
//Insert one char from stringstream
public void Insert(char ch)
{
if (map.containsKey(ch)) {
int time = map.get(ch);
time++;
map.put(ch, time);
} else {
map.put(ch, 1);
}
}
//return the first appearence once char in current stringstream
public char FirstAppearingOnce()
{
for (Map.Entry<Character, Integer> set:map.entrySet()) {
if (set.getValue() == 1)
return set.getKey();
}
return '#';
}
}
- 链表中环的入口结点
-
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}
*/
public class Solution {
public ListNode MeetingNode(ListNode pHead){
if (pHead == null)
return null;
// nodeSlow 走一步
ListNode nodeSlow = pHead.next;
if (nodeSlow == null)
return null;
// nodeFast 走两步
ListNode nodeFast = nodeSlow.next;
while (nodeSlow != null && nodeFast != null) {
if (nodeSlow == nodeFast) {
return nodeFast;
}
nodeSlow = nodeSlow.next;
nodeFast = nodeFast.next;
if (nodeFast != null) {
nodeFast = nodeFast.next;
}
}
return null;
}
public ListNode EntryNodeOfLoop(ListNode pHead){
if (pHead == null)
return null;
// 找到相遇的节点
ListNode meetingNode = MeetingNode(pHead);
if (meetingNode == null)
return null;
// 找到环的节点数
ListNode Node = meetingNode;
int count = 1;
// 绕一圈
while (Node.next != meetingNode) {
Node = Node.next;
count++;
}
// 定义两个节点,前者比后者快n个节点,当它们相遇时,即得到环的入口
ListNode node1 = pHead;
ListNode node2 = pHead;
for (int i=1;i<=count;i++) {
node1 = node1.next;
}
while (node1 != node2) {
node1 = node1.next;
node2 = node2.next;
}
return node1;
}
}
- 删除链表中重复的结点
-
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}
*/
public class Solution {
public ListNode deleteDuplication(ListNode pHead)
{
if (pHead == null)
return pHead;
ListNode pPreNode = null;
ListNode pNode = pHead;
while (pNode!=null) {
ListNode pNextNode = pNode.next;
//标记
boolean flag = false;
if (pNextNode!=null && pNode.val == pNextNode.val)
flag = true;
// 当前节点和下一节点不同。链表向前走一步,pPreNode重新赋值
if(!flag) {
// 没有值相同的,向前移动一步
pPreNode = pNode;
pNode = pNode.next;
} else {
// 删除 vaule 值相等的节点
int val = pNode.val;
ListNode toBeDelNode = pNode;
while (toBeDelNode!=null && toBeDelNode.val == val) {
// 链表删除某个节点
pNextNode = toBeDelNode.next;
toBeDelNode = pNextNode;
}
// 前面没有节点
if (pPreNode == null)
pHead = pNextNode;
else
pPreNode.next = pNextNode;
pNode = pNextNode;
}
}
return pHead;
}
}
- 二叉树的下一个结点
-
/*
public class TreeLinkNode {
int val;
TreeLinkNode left = null;
TreeLinkNode right = null;
TreeLinkNode next = null;
TreeLinkNode(int val) {
this.val = val;
}
}
*/
public class Solution {
public TreeLinkNode GetNext(TreeLinkNode pNode)
{
// 如果 pNode为空,返回 null
if (pNode == null) {
return null;
}
// 如果 pNode存在右子树,找右子树最左的节点
if (pNode.right != null) {
// 不存在左节点
pNode = pNode.right;
// 存在左节点,找最左的节点
while (pNode.left != null) {
// 遍历寻找
pNode = pNode.left;
}
return pNode;
// 如果 pNode不存在右子树,节点父节点的左子节点等于 pNode
} else if (pNode.next != null && pNode.right == null && pNode.next.left == pNode) {
return pNode.next;
// 如果 pNode不存在右子树,节点父节点的右子节点等于 pNode
} else if (pNode.next != null && pNode.right == null && pNode.next.right == pNode) {
// 是否存在父节点有左子节点
while (pNode.next != null && pNode.next.left != pNode) {
// 遍历寻找
pNode = pNode.next;
}
return pNode.next;
} else {
return pNode.next;
}
}
}
- 对称的二叉树
-
/*
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
boolean isSymmetrical(TreeNode pRoot)
{
return isSymmetrical(pRoot, pRoot);
}
boolean isSymmetrical(TreeNode pRoot1, TreeNode pRoot2){
if (pRoot1 == null && pRoot2 == null)
return true;
if (pRoot1 == null || pRoot2 == null)
return false;
if (pRoot1.val != pRoot2.val)
return false;
return isSymmetrical(pRoot1.left, pRoot2.right) && isSymmetrical(pRoot1.right, pRoot2.left);
}
}
- 按之字形顺序打印二叉树
-
import java.util.ArrayList;
import java.util.Stack;
/*
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
public ArrayList<ArrayList<Integer> > Print(TreeNode pRoot) {
int layer = 1;
Stack<TreeNode> stackOdd = new Stack<>();
Stack<TreeNode> stackEven = new Stack<>();
ArrayList<ArrayList<Integer>> list = new ArrayList<ArrayList<Integer>>();
if (pRoot == null) {
return list;
} else {
stackOdd.push(pRoot);
while (!stackOdd.isEmpty() || !stackEven.isEmpty()) {
// 奇数层
if (layer%2 != 0) {
ArrayList<Integer> temp = new ArrayList<Integer>();
while (!stackOdd.isEmpty()) {
TreeNode node = stackOdd.pop();
temp.add(node.val);
System.out.print(node.val);
if (node.left!=null)
stackEven.add(node.left);
if (node.right!=null)
stackEven.add(node.right);
}
if (!temp.isEmpty()) {
list.add(temp);
layer++;
}
} else {
ArrayList<Integer> temp = new ArrayList<Integer>();
while (!stackEven.isEmpty()) {
TreeNode node = stackEven.pop();
System.out.print(node.val);
temp.add(node.val);
if (node.right!=null)
stackOdd.add(node.right);
if (node.left!=null)
stackOdd.add(node.left);
}
if (!temp.isEmpty()) {
list.add(temp);
layer++;
}
}
}
}
return list;
}
}
- 把二叉树打印成多行
-
import java.util.ArrayList;
/*
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
static ArrayList<ArrayList<Integer> > Print(TreeNode pRoot) {
ArrayList<ArrayList<Integer>> llist = new ArrayList<ArrayList<Integer>>();
// 列表
ArrayList<Integer> list = new ArrayList<>();
// 队列
ArrayList<TreeNode> queue = new ArrayList<>();
if (pRoot == null) {
return llist;
} else {
// 先进
queue.add(pRoot);
// 定义当前打印节点数和下层打印节点数
int curPrintNode = 1;
int nextPrintNode = 0;
while (queue.size()!=0) {
// 先出
TreeNode temp = queue.remove(0);
// 找左右节点
if (temp.left!=null) {
queue.add(temp.left);
nextPrintNode++;
}
if (temp.right!=null) {
queue.add(temp.right);
nextPrintNode++;
}
// 将值添加到list
list.add(temp.val);
System.out.print(temp.val);
curPrintNode--;
if (curPrintNode == 0) {
llist.add(list);
list = new ArrayList<>();
System.out.println();
curPrintNode = nextPrintNode;
nextPrintNode = 0;
}
}
if (!list.isEmpty()) {
llist.add(list);
}
}
return llist;
}
}
- 序列化二叉树
-
/*
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
public int index = -1;
String Serialize(TreeNode root) {
StringBuffer sb = new StringBuffer();
if (root == null) {
sb.append("#,");
return sb.toString();
}
sb.append(root.val + ",");
sb.append(Serialize(root.left));
sb.append(Serialize(root.right));
return sb.toString();
}
TreeNode Deserialize(String str) {
index++;
// 记录字符串长度,并判断
int len = str.length();
if (index > len) {
return null;
}
// 重建二叉树
TreeNode node = null;
// 将字符串分割
String[] strr = str.split(",");
if (!strr[index].endsWith("#")) {
node = new TreeNode(Integer.valueOf(strr[index]));
node.left = Deserialize(str);
node.right = Deserialize(str);
}
return node;
}
}
- 二叉搜索树的第k个结点
-
/*
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
public int count = 0;
TreeNode KthNode(TreeNode pRoot, int k) {
if (pRoot != null) {
TreeNode left = KthNode(pRoot.left, k);
if (left != null) {
return left;
}
if (++count == k)
return pRoot;
TreeNode right = KthNode(pRoot.right, k);
if (right != null)
return right;
}
return null;
}
}
- 数据流中的中位数
-
import java.util.Comparator;
import java.util.PriorityQueue;
public class Solution {
PriorityQueue<Integer> minHead = new PriorityQueue<>();
// 优先队列默认是最小堆,反转实现最大堆
PriorityQueue<Integer> maxHead = new PriorityQueue<>(15, new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
// TODO Auto-generated method stub
return o2.compareTo(o1);
}
});
int count = 0;
public void Insert(Integer num) {
// 如果是偶数时插入最小堆
if (count%2 == 0) {
maxHead.offer(num);
Integer temp = maxHead.poll();
minHead.offer(temp);
} else {
minHead.offer(num);
Integer temp = minHead.poll();
maxHead.offer(temp);
}
count++;
}
public Double GetMedian() {
if (count%2 == 0) {
return (maxHead.peek() + minHead.peek())/2.0;
} else {
return new Double(minHead.peek());
}
}
}
- 滑动窗口的最大值
-
import java.util.ArrayList;
import java.util.LinkedList;
public class Solution {
public ArrayList<Integer> maxInWindows(int [] num, int size)
{
ArrayList<Integer> list = new ArrayList<>();
if (num == null || num.length < 0 || size < 1 || size > num.length)
return list;
LinkedList<Integer> index = new LinkedList<>();
for (int i = 0; i < size; i++) {
while (!index.isEmpty() && num[i] > num[index.getLast()])
index.removeLast();
index.addLast(i);
}
for (int i = size - 1; i < num.length; i++) {
while (!index.isEmpty() && num[i] > num[index.getLast()])
index.removeLast();
index.addLast(i);
if (i - index.getFirst() + 1 > size)
index.removeFirst();
list.add(num[index.getFirst()]);
}
return list;
}
}
- 矩阵中的路径
-
public class Solution {
public boolean hasPath(char[] matrix, int rows, int cols, char[] str) {
if (matrix==null || matrix.length<=0 || rows<0 || cols<0 || str == null || str.length<0) {
return false;
}
// 新建一个用于判断是否已经 visited 过的 boolean 数组
boolean[] visited = new boolean[matrix.length];
// 定义路径长度
int pathLen = 0;
// 循环起始点
for (int row=0; row<rows; row++)
for (int col=0; col<cols; col++) {
// 如果方法 hasPathCore能找到指定路径,返回 True
if (hasPathCore(matrix, rows, cols, str, row, col, pathLen, visited)) {
System.out.println("True");
return true;
}
}
return false;
}
public boolean hasPathCore(char[] matrix, int rows, int cols, char[] str, int row, int col, int pathLen, boolean[] visited) {
System.out.print(pathLen+"==");
System.out.println(str.length);
boolean hasPathFlag = false;
//终止条件,找到所有路径
if (pathLen == str.length) {
System.out.println("true");
return true;
}
//边界设置,满足的话,路径长度加1,设置为已经visit
if (row>=0&&col>=0&&row<rows&&col<cols&&matrix[row*cols+col]==str[pathLen]&&!visited[row*cols+col]) {
pathLen=pathLen+1;
visited[row*cols+col] = true;
//递归上下左右,返回True或False
hasPathFlag = hasPathCore(matrix,rows,cols,str,row,col+1,pathLen,visited)||
hasPathCore(matrix,rows,cols,str,row,col-1,pathLen,visited)||
hasPathCore(matrix,rows,cols,str,row+1,col,pathLen,visited)||
hasPathCore(matrix,rows,cols,str,row-1,col,pathLen,visited);
if (!hasPathFlag) {
//False的话回退
pathLen=pathLen-1;
visited[row*cols+col] = false;
}
}
// 返回 hasPath
return hasPathFlag;
}
}
- 机器人的运动范围
-
public class Solution {
public int movingCount(int threshold, int rows, int cols) {
// 边界判断
if (threshold<=0 && rows<=0 && cols<=0)
return 0;
//初始 visited 矩阵
boolean[] visited = new boolean[rows*cols];
for (int i = 0; i < visited.length; i++) {
visited[i] = false;
}
// 调用 movingCountCore判断
int count = movingCountCore(threshold, rows, cols, 0, 0, visited);
// 返回 count
return count;
}
public int movingCountCore(int threshold, int rows, int cols, int row, int col, boolean[] visited) {
// 边界判断
if (threshold<=0 && rows<=0 && cols<=0 && row>rows && col>cols)
return 0;
int count = 0;
// 先判断是否会超过 threshold 值
if (check(threshold, rows, cols, row, col, visited)) {
// 标记 visited, 注意是 row*cols+col
visited[row*cols+col] = true;
// 回溯调用
count = 1 + movingCountCore(threshold, rows, cols, row+1, col, visited)
+ movingCountCore(threshold, rows, cols, row-1, col, visited)
+ movingCountCore(threshold, rows, cols, row, col+1, visited)
+ movingCountCore(threshold, rows, cols, row, col-1, visited);
}
return count;
}
boolean check(int threshold, int rows, int cols, int row, int col, boolean[] visited) {
// 判断当前位置每个数累积之和
int max = getDigitSum(row)+getDigitSum(col);
// 边界判断、最大值判断和 visited判断
if (threshold>0 && row>=0 && col>=0 && row<rows && col<cols && max<=threshold && !visited[row*cols+col] )
return true;
return false;
}
int getDigitSum(int number) {
int sum = 0;
while (number>0) {
// 求每一位的数,累加
sum = sum + number%10;
number = number/10;
}
return sum;
}
}