@huangyichun
2018-04-04T11:54:20.000000Z
字数 39473
阅读 1249
算法
//建议画个图理解下
public class Solution {
public boolean Find(int target, int [][] array) {
if(array==null || array.length == 0){
return false;
}
int row = 0;
int col = array[0].length-1; //数组最后一列的下标
while(row <=array.length-1 && col >=0){
if(array[row][col] > target){//当该列最小的一个值都大于target
col --; //向左移一列
}else if(array[row][col] < target){//当该最小的一个小于target
row ++; //向下移一行
}else{ //如果该值等于target,返回true
return true;
}
}
return false;
}
}
public class Solution {
public String replaceSpace(StringBuffer str) {
if(str == null || str.length() <= 0){
return "";
}
int spaceCount = 0;
for(int i=0; i<str.length(); i++){//计算空格个数
if(str.charAt(i)==' '){
spaceCount++;
}
}
//设置初始下标
int index = str.length()-1;
int length = str.length()+spaceCount * 2;//设置新的StringBuilder大小
//新StringBuilder最后一个字符下标
int newIndex = length - 1;
str.setLength(length);
while(index >=0){
//当前下标的字符
char c = str.charAt(index);
if(c != ' '){
str.setCharAt(newIndex--, c);
}else{
str.setCharAt(newIndex--,'0');
str.setCharAt(newIndex--,'2');
str.setCharAt(newIndex--,'%');
}
index --;
}
return str.toString();
}
}
import java.util.ArrayList;
public class Solution {
private ArrayList<Integer> list = new ArrayList<>();
public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
if(listNode != null){
printListFromTailToHead(listNode.next);//递归
list.add(listNode.val);
}
return list;
}
}
import java.util.*;
public class Solution {
private Map<Integer,Integer> map = new HashMap<>();
public TreeNode reConstructBinaryTree(int [] pre,int [] in) {
for(int i=0; i<pre.length; i++){
map.put(in[i],i);//存放中序中值对应的下标
}
return rebuild(pre,0, pre.length-1, 0, pre.length-1);
}
public TreeNode rebuild(int[] pre, int pi, int pj, int ni, int nj){
if(pi>pj)
return null;
int index = map.get(pre[pi]);//前序该值该中序中的位置
TreeNode root = new TreeNode(pre[pi]);//创建根节点
root.left = rebuild(pre, pi+1, pi+ index-ni, ni, index-1);//建立根节点的左子树
root.right = rebuild(pre,pi+index-ni+1,pj, index+1, nj);//建立根节点右子树
return root;//返回根节点
}
}
import java.util.Stack;
import java.util.*;
public class Solution {
Stack<Integer> stack1 = new Stack<Integer>();//保存插入
Stack<Integer> stack2 = new Stack<Integer>();//处理删除
public void push(int node) {
stack1.push(node);
}
//如果stack2不为空,直接从stack2删除
//如果stack2为空,将stack1的内容,删除放入stack2中
public int pop() {
if(stack2.size() == 0 && stack1.size() == 0){
throw new EmptyStackException();
}
if(stack2.size() == 0){
while(!stack1.isEmpty()){
stack2.push(stack1.pop());
}
}
return stack2.pop();
}
}
import java.util.ArrayList;
public class Solution_1 {
public static void main(String[] args) {
int[] array = {4,1,1, 2, 3};
int i = minNumberInRotateArray(array);
System.out.println(i);
}
//本题考查二分查找
public static int minNumberInRotateArray(int [] array) {
if(array == null || array.length == 0){
return 0;
}
if(array.length == 1){
return array[0];
}
int index1 = 0;
int index2 = array.length-1;
int mid = index1;
while(array[index1] >= array[index2]){
mid = (index2-index1) / 2;
if(index2-index1 == 1){ //当两个相邻时
mid = index2;
break;
}
if(array[index1] <= array[mid] && array[mid] > array[index2]){// 3 3 3 0 2情况
index1 = mid;
}else if(array[index2] >= array[mid] && array[index1] > array[mid]){// 3 0 0 0 2情况
index2 = mid;
}else{// 3 3 3 0 3, 3 0 0 0 3两种情况无法判断哪个属于旋转部分
mid = getMin(array,index1, index2);//采用顺序查找
break;
}
}
return array[mid];
}
public static int getMin(int[] array, int index1, int index2){
int min = index1;
for(int i=index1+1; i<= index2; i++){
if(array[min] > array[i]){
min = i;
}
}
return min;
}
}
public class Solution {
public int Fibonacci(int n) {
if(n < 2){
return n;
}
int f1 = 0;
int f2 = 1;
int f = f2;
for(int i=2; i<= n; i++){
f = f1 + f2;
f1 = f2;
f2 = f;
}
return f2;
}
}
public class Solution {
public int JumpFloor(int target) {
if(target <= 2){
return target;
}
int f1 = 1;
int f2 = 2;
int f = f2;
for(int i=3; i<=target; i++){
f = f1 +f2;
f1 = f2;
f2 = f;
}
return f2;
}
}
import java.util.*;
public class Solution {
public int JumpFloorII(int target) {
//f(n) = f(n-1) + f(n-2) + ... + f(1); f(n) = 2 * f(n-1);
//f(1) = 1 f(2) = 2 , f(n-1) = 2 xy(n-1)
return (int)Math.pow(2,target-1);
}
}
public class Solution {
public int RectCover(int target) {
if(target <=2){
return target;
}
int f1 = 1;
int f2 = 2;
int sum = 0;
for(int i=3; i<= target; i++){
sum = f1 + f2;
f1 = f2;
f2 = sum;
}
return sum;
}
}
## 位运算 ##
/**负数是用补码表示的,补码求法位原码取反加一(原码是数的绝对值的二进制)
补码转换成原码为:取反加一(符号位不变)
例如: -16 二进制8位的 (原码)0001 0000 反码:1110 1111 补码:1111 0000
然后-16 / 2 = -8 相当于补码右移一位: 1111 1000 反码:1000 0111 原码: 1000 1000 = -8
移位运算:右移时,如果是负数,左边补1
*/
public class Solution {
public int NumberOf1(int n) {
//思路: 一个数减去1,然后与上这个数,这样这个数从右到左的第一个1变为0
int count = 0;
while(n != 0){
++ count;
n = (n-1) & n;
}
return count;
}
}
public class Solution {
public double Power(double base, int exponent) {
if(equal(base,0.0)){
throw new IllegalArgumentException("底数不能为0");
}
int absExponent = exponent;
if(exponent < 0){//将指数先转换成正的
absExponent = -exponent;
}
double result = PowerWithUnsignedExponent(base, absExponent);
if(exponent < 0){//如果指数为负
result = 1.0 / result;
}
return result;
}
//非递归下的求法
public static double PowerWithUnsignedExponent(double base, int exponent){
double result = 1;
double temp = base;
while(exponent != 0){
if((exponent & 0x1) == 1){
result =result * temp;
}
exponent >>= 1;
temp *= temp;
}
return result;
}
public boolean equal(double num1, double num2){
if(num1-num2 > -0.0000001 && num1-num2 < 0.0000001){
return true;
}else{
return false;
}
}
}
public class Solution {
public void reOrderArray(int [] array) {
if(array == null || array.length == 0){
return ;
}
int begin = 0;
int end = begin+1;
while(end < array.length){
while(begin < array.length-1 && (array[begin] & 0x1) != 0){//找到偶数
begin ++;
}
end = begin +1;
while(end <= array.length-1 && (array[end] & 0x1) == 0){//找到奇数
end ++;
}
if(end == array.length)
break;
int temp = array[end];
for(int i=end; i > begin; i--){//偶数后移
array[i] = array[i-1];
}
array[begin] = temp;
begin ++;
}
}
}
public class Solution {
public ListNode FindKthToTail(ListNode head,int k) {
if(head == null || k <= 0){
return null;
}
ListNode pHead = head;
ListNode pBehind = null;
for(int i=0; i<k-1; i++){//先走k-1个节点
if(pHead.next != null){
pHead = pHead.next;
}else{
return null;
}
}
pBehind = head;
while(pHead.next != null){
pHead = pHead.next;
pBehind = pBehind.next;
}
return pBehind;
}
}
/*
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 preNode = null;
ListNode nextNode = null;
while(head != null){
nextNode = head.next;
head.next = preNode;
preNode = head;
head = nextNode;
}
return preNode;
}
}
public class Solution {
public ListNode Merge(ListNode list1,ListNode list2) {
if(list1 == null)
return list2;
else if(list2 == null)
return list1;
ListNode head = null;
//递归思想实现
if(list1.val < list2.val){
head = list1;
head.next = Merge(list1.next, list2);
}else{
head = list2;
head.next = Merge(list1, list2.next);
}
return head;
}
}
public class Solution {
public boolean HasSubtree(TreeNode root1,TreeNode root2) {
//使用先序遍历找到root1 == root2
//当root1 = root2时,采用先序遍历判断两个子树是否相同
boolean isChild = false;
if(root1 == null || root2 == null){
return false;
}
if(root1.val == root2.val){
isChild = isTheSame(root1, root2);
}
if(!isChild){
isChild = HasSubtree(root1.left,root2);
}
if(!isChild){
isChild = HasSubtree(root1.right,root2);
}
return isChild;
}
public boolean isTheSame(TreeNode root1, TreeNode root2){
if(root2 == null) //递归结束条件
return true;
if(root1 == null)
return false;
if(root1.val != root2.val)
return false;
return isTheSame(root1.left,root2.left) && isTheSame(root1.right,root2.right);
}
}
public class Solution {
public void Mirror(TreeNode root) {
if(root == null){//递归退出条件
return;
}
if(root.left == null && root.right == null)//递归退出条件
return;
//交换左右子树
TreeNode tmp = root.left;
root.left = root.right;
root.right = tmp;
if(root.left != null){
Mirror(root.left);
}
if(root.right != null){
Mirror(root.right);
}
}
}
//这题没有按照剑指Offer来
// 1 2 3 4
// 5 6 7 8
// 9 10 11 12
// 13 14 15 16
// 每先从上右下左各取3个数,刚好取完外圈
//当到达最后一圈时可能有如下几种情况:
// a b c 剩下一个长大于宽的矩形
//-----------------------------------
// a 剩下一个宽大于长的矩形
// b
// c
// ---------------------------------
// a 剩下一个值
import java.util.ArrayList;
public class Solution {
public ArrayList<Integer> printMatrix(int [][] matrix) {
ArrayList<Integer> list = new ArrayList<>();
if(matrix == null || (matrix.length <=0 && matrix[0].length == 0))
return list;
int columns = matrix[0].length;
int rows = matrix.length;
int rowStart = 0; //第一行
int rowEnd = rows-1; //最后一行
int colStart = 0; //第一列
int colEnd = columns - 1; //最后一列
while(rowStart <= rowEnd && colStart <= colEnd){
if(rowStart < rowEnd && colStart < colEnd){
for(int i= colStart; i<= colEnd-1; i++){//左到右第一行
list.add(matrix[rowStart][i]);
}
for(int i= rowStart; i<= rowEnd-1; i++){//上到下第一列
list.add(matrix[i][colEnd]);
}
for(int i=colEnd; i >= colStart + 1; i--){//右到左第一行
list.add(matrix[rowEnd][i]);
}
for(int i=rowEnd; i >= rowStart + 1; i--){//下到上第一列
list.add(matrix[i][colStart]);
}
}else if(colStart < colEnd && rowStart == rowEnd){//剩下一个长大于宽的矩形
for(int i= colStart; i<= colEnd; i++){
list.add(matrix[rowStart][i]);
}
}else if(rowStart < rowEnd && colStart == colEnd){//剩下一个宽大于长的矩形
for(int i = rowStart; i<= rowEnd; i++){
list.add(matrix[i][colStart]);
}
}else{// 剩下一个值
list.add(matrix[rowStart][colStart]);
}
rowStart ++;
colStart ++;
rowEnd --;
colEnd --;
}
return list;
}
}
import java.util.Stack;
public class Solution {
private Stack<Integer> minStack = new Stack();//存放最小的
private Stack<Integer> stack = new Stack();//存放添加的
public void push(int node) {
if(minStack.isEmpty() || node < minStack.peek())
minStack.push(node);
stack.push(node);
}
public void pop() {
if(stack.isEmpty())
return;
if(!minStack.isEmpty() && minStack.peek() == stack.peek()){
minStack.pop();
}
stack.pop();
}
public int top() {
return stack.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) {
Stack<Integer> stack = new Stack();
int index = 0;
for(int i=0; i<popA.length; i++){
int num = popA[i];
if(stack.isEmpty()){//栈为空时添加节点
stack.push(pushA[index++]);
}
while(stack.peek()!= num && index < pushA.length){
stack.push(pushA[index++]);
}
if(stack.peek()!=num && index >= pushA.length)//当栈顶元素不等于num且pushA元素已经都入栈
return false;
stack.pop();
}
return true;
}
}
/**
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();
LinkedList<TreeNode> queue = new LinkedList();
if(root == null)
return list;
queue.offer(root);
while(!queue.isEmpty()){
TreeNode node = queue.poll();
list.add(node.val);
if(node.left != null){
queue.offer(node.left);
}
if(node.right != null){
queue.offer(node.right);
}
}
return list;
}
}
public class Solution {
public boolean VerifySquenceOfBST(int [] sequence) {
if(sequence == null || sequence.length <=0)
return false;
return isPostBST(sequence, 0, sequence.length-1);
}
public boolean isPostBST(int[] array, int start, int end){
//根节点的值
int root = array[end];
//找到左子树是否满足后序遍历
int i=start;
for(; i<end; i++){
if(array[i] > root){
break;
}
}
int j=i;
for(; j<end; j++){
if(array[j] < root)
return false;
}
boolean left = true;
//判断左子树是不是二叉搜索树
if(i > start){
left = isPostBST(array,start, start + i -1);
}
boolean right = true;
if(j < end){
right = isPostBST(array, start+i, end-1);
}
return left && right;
}
}
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 {
private ArrayList<ArrayList<Integer>> roads = new ArrayList();//存储所有路径
private ArrayList<Integer> road = new ArrayList();//存放当前路径
public ArrayList<ArrayList<Integer>> FindPath(TreeNode root,int target) {
if(root == null)
return roads;
road.add(root.val);
if(root.left == null && root.right == null){//当到达叶节点时
if(target == root.val)
roads.add(new ArrayList<>(road));
}
if(root.left != null){//当左子树不为空
FindPath(root.left, target-root.val);
}
if(root.right != null){//当右子树不为空
FindPath(root.right, target-root.val);
}
road.remove(road.size()-1);
return roads;
}
}
/*
public class RandomListNode {
int label;
RandomListNode next = null;
RandomListNode random = null;
RandomListNode(int label) {
this.label = label;
}
}
*/
public class Solution {
//分成三步1.复制每个节点放置在该节点的后面
//2.修改节点的random指针
//3.修改节点的next指针
public static RandomListNode Clone(RandomListNode pHead)
{
if(pHead == null)
return null;
copy(pHead);
changeRandom(pHead);
return changeNext(pHead);
}
public static RandomListNode changeNext(RandomListNode pHead){//修改next指针
RandomListNode root = pHead;
RandomListNode head = pHead.next;
while(root != null){
RandomListNode copy = root.next;
root.next = copy.next;
root = copy.next;
if(root != null)
copy.next = root.next;
else
copy.next = null;
}
return head;
}
public static void changeRandom(RandomListNode pHead){//修改随机指针
RandomListNode root = pHead;
while(root != null){
if(root.random != null){
root.next.random = root.random.next;
}
root = root.next.next;
}
}
public static void copy(RandomListNode pHead){//复制节点
RandomListNode root = pHead;
while(root != null){
RandomListNode node = new RandomListNode(root.label);//复制节点
node.next = root.next;
node.random = root.random;
root.next = node;//修改原节点吓一跳指针
root = node.next;//root指向下一个节点
}
}
}
/**
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
private TreeNode head = null;//记录链表起始节点
public TreeNode Convert(TreeNode pRootOfTree) {
if(pRootOfTree == null){
return null;
}
if(pRootOfTree.left == null && pRootOfTree.right == null)
return pRootOfTree;
if(head == null){//找到初始节点
head = pRootOfTree;
while(head.left != null){
head = head.left;
}
}
Convert(pRootOfTree.left);//左子树构成一个双向链表
Convert(pRootOfTree.right);//右子树构成一个双向链表
TreeNode leftLast = null;
if(pRootOfTree.left != null){//找到左子树最右边一个就节点
leftLast = pRootOfTree.left;
while(leftLast.right != null){
leftLast = leftLast.right;
}
}
TreeNode rightFirst = null;
if(pRootOfTree.right != null){//找到右子树最左边的一个点
rightFirst = pRootOfTree.right;
while(rightFirst.left != null){
rightFirst = rightFirst.left;
}
}
if(leftLast != null){//左子树最大的点不为空
leftLast.right = pRootOfTree;
pRootOfTree.left = leftLast;
}
if(rightFirst != null){//右子树最小的点不为空
rightFirst.left = pRootOfTree;
pRootOfTree.right = rightFirst;
}
return head;
}
}
import java.util.*;
public class Solution {
public static ArrayList<String> Permutation(String str) {
if(str == null)
return null;
ArrayList<String> list = new ArrayList<>();
char[] chars = str.toCharArray();
list = allSort(chars, 0, list);
Collections.sort(list);
return list;
}
public static ArrayList<String> allSort(char[] chars, int index, ArrayList<String> list){
if(index == chars.length-1){
list.add(String.valueOf(chars));
return list;
}
for(int i=index; i< chars.length; i++){
if(i != index && chars[i] == chars[index])//当要交换的值相同时
continue;
exChangeChars(index, i, chars); //修改第一个与后面的位置
allSort(chars,index+1,list);
exChangeChars(index, i, chars);//修改成原来的数组
}
return list;
}
/**
* 交换两个字符数组的位置
* @param index1
* @param index2
* @param chars
*/
public static void exChangeChars(int index1, int index2, char[] chars){
char tmp =chars[index1];
chars[index1] = chars[index2];
chars[index2] = tmp;
}
}
public class Solution {
public int MoreThanHalfNum_Solution(int [] array) {
if(array == null || array.length == 0)
return 0;
int num = 0;
int count = 0;
for(int i=0; i<array.length; i++){
if(count == 0){
num = array[i];
count = 1;
}else if(num == array[i]){
count++;
}else{
count--;
}
}
count = 0;
for(int i=0; i<array.length; i++){
if(array[i] == num)
count++;
}
if((count << 1) <= array.length){
return 0;
}
return num;
}
}
import java.util.*;
public class Solution {
public static ArrayList<Integer> GetLeastNumbers_Solution(int [] input, int k) {
ArrayList<Integer> list = new ArrayList<>();
if(input == null || k <=0 || input.length < k)
return list;
int start = 0;
int end = input.length -1;
int index = partition(input, start, end);
while(index != k-1){
if(index > k-1){
end = index-1;
index = partition(input,start,end);
}else{
start = index + 1;
index = partition(input,start,end);
}
}
for(int i=0; i<k; i++)
list.add(input[i]);
return list;
}
public static int partition(int[] array, int start, int end){
if(array == null || array.length <= 0 || start< 0 || end >= array.length)
throw new RuntimeException("输入不正确");
int index = (int)(Math.random() *(end-start +1)) + start;//获取随机数
swap(array,index,start);
while(start < end){
while(array[end] > array[start])
end --;
if(start < end){
swap(array, start, end);
start ++;
}
while(array[start] < array[end])
start ++;
if(start < end){
swap(array,start, end);
end--;
}
}
return start;
}
public static void swap(int[] array, int index, int start){//交换数组位置
int tmp = array[index];
array[index] = array[start];
array[start] = tmp;
}
}
public class Solution {
public int FindGreatestSumOfSubArray(int[] array) {
if(array== null || array.length <=0)
throw new RuntimeException("数组长度不正确");
int max = Integer.MIN_VALUE;
int curSum = Integer.MIN_VALUE;
for(int i=0; i<array.length; i++){
if(curSum < 0)
curSum = array[i];
else
curSum = array[i] + curSum;
if(curSum > max)
max = curSum;
}
return max;
}
}
import java.util.*;
public class Solution {
public int NumberOf1Between1AndN_Solution(int n) {
if(n <= 0)
return 0;
int high, low, cur, i = 1;
high = n;
int count = 0;
while(high != 0){
high = n / (int)Math.pow(10, i);
int tmp = n % (int)Math.pow(10,i);
cur = tmp / (int)Math.pow(10,i-1);
low = tmp % (int)Math.pow(10,i-1);
if(cur > 1){
count += (high+1) * (int)Math.pow(10, i-1);
}else if(cur == 1){
count += high * (int)Math.pow(10,i-1) + low +1;
}else{
count+= high * (int)Math.pow(10,i-1);
}
i++;
}
return count;
}
}
import java.util.ArrayList;
import java.util.*;
public class Solution {
public String PrintMinNumber(int [] numbers) {
ArrayList<String> list = new ArrayList<>();
for(int i=0; i<numbers.length; i++){
list.add(Integer.toString(numbers[i]));
}
Collections.sort(list,new Comparator<String>(){
public int compare(String o1, String o2){
String s1 = o1 + o2;
String s2 = o2 + o1;
return s1.compareTo(s2);
}
}
);
StringBuilder sb = new StringBuilder();
for(String s : list){
sb.append(s);
}
return sb.toString();
}
}
import java.util.*;
public class Solution {
public int GetUglyNumber_Solution(int index) {
if(index <= 0){
return 0;
}
List<Integer> list = new ArrayList();
list.add(1);
int num1, num2, num3;
int index1=0,index2=0,index3=0;
while(list.size() < index){
num1 = list.get(index1) * 2;
num2 = list.get(index2) * 3;
num3 = list.get(index3) * 5;
int min = Math.min(num1, Math.min(num2,num3));
list.add(min);
if(min == num1)
index1 ++;
if(min == num2)
index2 ++;
if(min == num3)
index3 ++;
}
return list.get(index-1);
}
}
import java.util.*;
public class Solution {
public int FirstNotRepeatingChar(String str) {
char[] chars = str.toCharArray();//转换成字符数组
LinkedHashMap<Character,Integer> map = new LinkedHashMap<>();
for(int i=0; i<chars.length; i++){
if(map.containsKey(chars[i])){
int value = map.get(chars[i]);
map.put(chars[i],value+1);
}else{
map.put(chars[i],1);
}
}
for(int i=0; i<chars.length; i++){
if(map.get(chars[i]) == 1)
return i;
}
return -1;
}
}
public class Solution {
private int count = 0;
private int[] copy;
public int InversePairs(int [] array) {
if(array == null || array.length == 0)
return 0;
copy = new int[array.length];
sort(array, 0, array.length-1);
return count;
}
public void sort(int[] array, int start, int end){
if(start >= end)
return;
int mid = (start + end) / 2;
sort(array, start, mid);
sort(array,mid+1, end);
merger(array, start, mid, end);
}
public void merger(int[] array, int start, int mid, int end){
int i = start, j = mid+1;
for(int k=i; k <= end; k++){
copy[k] = array[k]; //复制需要合并的数组
}
for(int k = start; k <= end; k++){
if(i > mid) array[k] = copy[j++]; //最半边取尽
else if(j > end) array[k] = copy[i++]; //右半边取尽
else if(copy[i] <= copy[j]) array[k] = copy[i++]; //左边小于等于右边
else {
array[k] = copy[j++];
count = (count + mid - i+1) % 1000000007;
}
}
}
}
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
public class Solution {
public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
if(pHead1 == null || pHead2 == null)
return null;
int length1 = getLength(pHead1);
int length2 = getLength(pHead2);
int lengthDif = length1 - length2;
ListNode longNode = pHead1;
ListNode shortNode = pHead2;
if(length2 > length1){
lengthDif = length2 - length1;
longNode = pHead2;
shortNode = pHead1;
}
for(int i=0; i<lengthDif; i++){//长链表后移lengthDif位
longNode = longNode.next;
}
while(longNode != null && shortNode != null && longNode != shortNode){
longNode = longNode.next;
shortNode = shortNode.next;
}
return longNode;
}
public int getLength(ListNode head){//获取链表长度
int length = 0;
ListNode pNode = head;
while(pNode != null){
length ++;
pNode = pNode.next;
}
return length;
}
}
public class Solution {
public int GetNumberOfK(int [] array , int k) {
if(array == null || array.length == 0)
return 0;
int left = getLeftIndex(array,k);
int right = getRightIndex(array, k);
if(left == -1 || right == -1)
return 0;
return right - left +1;
}
public int getLeftIndex(int[] array, int k){//获取左边第一个k下标
int low = 0, mid = 0, high = array.length-1;
while(low <= high){
mid = (low + high) / 2;
if(array[mid] > k){
high = mid - 1;
}else if(array[mid] < k){
low = mid +1;
}else{
if(mid > 0 && array[mid-1] == k){
high = mid-1;
}else{
return mid;
}
}
}
return -1;
}
public int getRightIndex(int[] array, int k){//获取左边第一个k下标
int low = 0, mid=0, high = array.length-1;
while(low <= high){
mid = (low+high) / 2;
if(array[mid] > k){
high = mid -1;
}else if(array[mid] < k){
low = mid +1;
}else{
if(mid < array.length-1 && array[mid+1] == k){
low = mid+1;
}else{
return mid;
}
}
}
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 left = TreeDepth(root.left);
int right = TreeDepth(root.right);
return left > right ? (left + 1) : (right + 1);
}
}
public class Solution {
boolean isBalanced = true;
public boolean IsBalanced_Solution(TreeNode root) {
getDeep(root);
return isBalanced;
}
public int getDeep(TreeNode root){
if(root == null)
return 0;
int left = getDeep(root.left);
int right = getDeep(root.right);
if(left - right > 1 || left - right < -1){
isBalanced = false;
}
return left > right ? left + 1 : right + 1;
}
}
//num1,num2分别为长度为1的数组。传出参数
//将num1[0],num2[0]设置为返回结果
public class Solution {
public void FindNumsAppearOnce(int [] array,int num1[] , int num2[]) {
if(array.length == 2){
num1[0] = array[0];
num2[1] = array[1];
}
int result = 0;
for(int i=0; i<array.length; i++){
result ^= array[i];
}
int index = findFirstBitIs1(result);
num1[0] = 0;
num2[0] = 0;
for(int i=0; i<array.length; i++){
if(isBit1(array[i], index)){
num1[0] ^= array[i];
}else{
num2[0] ^= array[i];
}
}
}
public boolean isBit1(int num, int indexBit){
num = num >> indexBit;
return (num & 1) == 1;
}
public int findFirstBitIs1(int num){//求两个出现一次数字的下标
int index = 0;
while((num & 1) == 0){
num = num >> 1;
++index;
}
return index;
}
}
import java.util.ArrayList;
public class Solution {
public ArrayList<ArrayList<Integer> > FindContinuousSequence(int sum) {
ArrayList<ArrayList<Integer>> list = new ArrayList<>();
if(sum < 3)
return list;
int small = 1;
int big = 2;
int mid = (sum + 1) / 2;
int curSum = big + small;
while(small < mid){
if(curSum == sum){
list.add(countinueSequence(small, big));
curSum -= small;
++ small;
}else if(curSum < sum){
++big;
curSum += big;
}else{
curSum -= small;
++small;
}
}
return list;
}
public ArrayList<Integer> countinueSequence(int small, int big){
ArrayList<Integer> list = new ArrayList<>();
for(int i=small; i<= big; i++){
list.add(i);
}
return list;
}
}
import java.util.ArrayList;
public class Solution {
public ArrayList<Integer> FindNumbersWithSum(int [] array,int sum) {
int first = 0, last = array.length-1;
int mulSum = Integer.MAX_VALUE;
ArrayList<Integer> list = new ArrayList<>();
while(first < last){
int numFirst = array[first];
int numLast = array[last];
if(numFirst + numLast < sum)
++first;
else if(numFirst + numLast > sum)
--last;
else{
if(numFirst * numLast < mulSum){
mulSum = numFirst * numLast;
list.clear();
list.add(numFirst);
list.add(numLast);
}
++first;
}
}
return list;
}
}
public class Solution {
public String LeftRotateString(String str,int n) {
if(str == null || str.length() == 0){
return "";
}
char[] chars = str.toCharArray();
int length = chars.length;
reverse(chars, 0, length-1);
n = n % length;
reverse(chars, 0, length - n -1);
reverse(chars, length -n, length-1);
return new String(chars);
}
public void reverse(char[] chars, int start, int end){//翻转
while(start < end){
char tmp = chars[start];
chars[start] = chars[end];
chars[end] = tmp;
++ start;
--end;
}
}
}
public class Solution {
public String ReverseSentence(String str) {
if(str == null || str.length() == 1)
return str;
char[] chars = str.toCharArray();
reverse(chars, 0, str.length()-1);
int start = 0;
for(int i=0; i<chars.length; ++i){
if(chars[i] == ' '){
reverse(chars, start, i-1);
start = i + 1;
}else if(i == chars.length-1){
reverse(chars, start, i);
}
}
return String.valueOf(chars);
}
public void reverse(char[] chars, int start, int end){//翻转
while(start < end){
char tmp = chars[start];
chars[start] = chars[end];
chars[end] = tmp;
++ start;
--end;
}
}
}
import java.util.*;
public class Solution {
public boolean isContinuous(int [] numbers) {
if(numbers == null || numbers.length < 1)
return false;
Arrays.sort(numbers);
int numberZero = 0;
int numberGap = 0;
for(int i=0; i<numbers.length && numbers[i] == 0; i++){
++numberZero ;
}
int small = numberZero;
int big = small + 1;
while(big < numbers.length){
if(numbers[small] == numbers[big])//对子
return false;
numberGap += numbers[big] - numbers[small] - 1;
small = big;
++big;
}
if(numberGap <= numberZero)
return true;
return false;
}
}
public class Solution {
public int LastRemaining_Solution(int n, int m) {
if(n < 1 || m < 1)
return -1;
int last = 0;
for(int i=2; i<=n; i++){
last = (last + m) % i;
}
return last;
}
}
public class Solution {
public int Sum_Solution(int n) {
int sum = n;
boolean bool = (sum>0) && (sum += Sum_Solution(n-1))>0;
return sum;
}
}
public class Solution {
public int Add(int num1,int num2) {
int sum = num1 ^ num2;
int carry = (num1 & num2) << 1;
sum += carry;
return sum;
}
}
public class Solution {
public int StrToInt(String str) {
if(str == null)
return 0;
boolean negative = false;//判断符号
int result = 0;
int i =0, len = str.length();
if(len > 0){
char firstChar = str.charAt(0);
if(firstChar < '0'){
if(firstChar == '-'){
negative = true;
}else if(firstChar != '+')
return 0;
if(len == 1)
return 0;
i++;
}
while(i < len){
char c = str.charAt(i++);
if(c < '0' || c > '9')
return 0;
if((negative && -result < Integer.MIN_VALUE) || (!negative && result > Integer.MAX_VALUE))
return 0;
result = result * 10 + (c - '0');
}
}else{
return 0;
}
return negative ? -result : result;
}
}
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 || numbers.length < 1)
return false;
for(int i=0; i<numbers.length; ++i){
if(numbers[i] < 0 || numbers[i] > length-1)
return false;
}
for(int i=0; i< length; ++i){
while(numbers[i] != i){
if(numbers[i] == numbers[numbers[i]]){
duplication[0] = numbers[i];
return true;
}
int temp = numbers[i];
numbers[i] = numbers[temp];
numbers[temp] = temp;
}
}
return false;
}
}
import java.util.ArrayList;
public class Solution {
public int[] multiply(int[] A) {
if(A == null || A.length < 1){
return null;
}
int[] array1 = new int[A.length];//保存前半部分矩阵
array1[0] = 1;
for(int i=1; i< A.length; i++){
array1[i] = array1[i-1] * A[i-1];
}
int[] array2 = new int[A.length];
array2[A.length-1] = array1[A.length-1]; // 设置最后一个值
int temp = 1;
for(int i=A.length-2; i>=0; i--){
temp *= A[i+1];
array2[i] = temp * array1[i];
}
return array2;
}
}
public class Solution {
public boolean match(char[] str, char[] pattern) {
if(str == null || pattern == null)
return false;
int strIndex = 0;
int patternIndex = 0;
return isMatchCode(str,pattern,strIndex, patternIndex);
}
/**
当模式中的第二个字符不是“*”时:
1、如果字符串第一个字符和模式中的第一个字符相匹配,那么字符串和模式都后移一个字符,然后匹配剩余的。
2、如果
字符串第一个字符和模式中的第一个字符相不匹配,直接返回false。
而当模式中的第二个字符是“*”时:
如果字符串第一个字符跟模式第一个字符不匹配,则模式后移2个字符,继续匹配。如果字符串第一个字符跟模式第一个字符匹配,可以有3种匹配方式:
1、模式后移2字符,相当于x*被忽略;
2、字符串后移1字符,模式后移2字符;
3、字符串后移1字符,模式不变,即继续匹配字符下一位,因为*可以匹配多位;
*/
public boolean isMatchCode(char[] str, char[] pattern, int strIndex, int patIndex){
if(strIndex == str.length && patIndex == pattern.length)
return true;
if(strIndex != str.length && patIndex == pattern.length)
return false;
if(patIndex+1<pattern.length && pattern[patIndex+1] == '*'){
if(strIndex != str.length &&(pattern[patIndex] ==str[strIndex] || pattern[patIndex] == '.')){
return isMatchCode(str,pattern,strIndex, patIndex+2) || isMatchCode(str,pattern,strIndex+1,patIndex+1)|| isMatchCode(str,pattern, strIndex+1, patIndex);
}else {
return isMatchCode(str, pattern, strIndex, patIndex+2);
}
}
if(strIndex != str.length && (pattern[patIndex] == str[strIndex] || pattern[patIndex] == '.')){
return isMatchCode(str,pattern, strIndex+1, patIndex+1);
}
return false;
}
}
public class Solution {
public boolean isNumeric(char[] str) {
String s = String.valueOf(str);
// * 匹配前一个字符0次或多次
// ? 匹配前面的0次或者1次
// . 配除换行符 \n 之外的任何单字符。要匹配 . ,请使用 \.
// + 匹配前面字符1次或多次
return s.matches("[\\+-]?[0-9]*(\\.[0-9]+)?([eE][\\+-]?[0-9]+)?");
}
}
import java.util.*;
public class Solution {
//Insert one char from stringstream
private LinkedHashMap<Character,Integer> map = new LinkedHashMap<>();
public void Insert(char ch)
{
if(map.containsKey(ch)){
int value = map.get(ch);
map.put(ch, value+1);
}else{
map.put(ch, 1);
}
}
//return the first appearence once char in current stringstream
public char FirstAppearingOnce()
{
for(Map.Entry<Character,Integer> entry : map.entrySet()){
if(entry.getValue() == 1)
return entry.getKey();
}
return '#';
}
}
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}
*/
public class Solution {
public ListNode EntryNodeOfLoop(ListNode pHead)
{
if(pHead == null)
return null;
ListNode p1 = pHead;
ListNode p2 = pHead;
while(p1 != null && p2.next != null){
p1 = p1.next;
p2 = p2.next.next;
if(p1 == p2){
p1 = pHead;
while(p1 != p2){
p1 = p1.next;
p2 = p2.next;
}
return p1;
}
}
return null;
}
}
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}
*/
public class Solution {
public static ListNode deleteDuplication(ListNode pHead) {
if(pHead == null)
return null;
ListNode head = new ListNode(-1);
head.next = pHead;
ListNode preNode = head;
ListNode pNode = head.next;
while(pNode != null && pNode.next != null){
if(pNode.val == pNode.next.val){
int value = pNode.val;
while(pNode != null && pNode.val == value)
pNode = pNode.next;
preNode.next = pNode;
}else{
preNode = pNode;
pNode = pNode.next;
}
}
return head.next;
}
}
/*
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)
{
if(pNode == null)
return null;
if(pNode.right != null){
pNode = pNode.right;
while(pNode.left != null)
pNode = pNode.left;
return pNode;
}else{
TreeLinkNode node = pNode.next;
while(node != null && node.right == pNode){
pNode = node;
node = node.next;
}
return node;
}
}
}
/*
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 root1, TreeNode root2){
if(root1 == null && root2 == null)
return true;
if(root1 == null || root2 == null)
return false;
if(root1.val != root2.val)
return false;
return isSymmetrical(root1.left,root2.right) && isSymmetrical(root1.right, root2.left);
}
}
import java.util.ArrayList;
import java.util.*;
/*
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) {
ArrayList<ArrayList<Integer>> list = new ArrayList<>();
if(pRoot == null)
return list;
LinkedList<TreeNode> stack1 = new LinkedList<>();
LinkedList<TreeNode> stack2 = new LinkedList<>();
stack1.push(pRoot);
int index = 1;
while(!stack1.isEmpty() || !stack2.isEmpty()){
ArrayList<Integer> arrayList = new ArrayList<>();
if(index == 1){
while(!stack1.isEmpty()){
TreeNode node = stack1.pop();
if(node.left != null){
stack2.push(node.left);
}
if(node.right != null){
stack2.push(node.right);
}
arrayList.add(node.val);
}
index = 2;
}else{
while(!stack2.isEmpty()){
TreeNode node = stack2.pop();
if(node.right != null){
stack1.push(node.right);
}
if(node.left != null){
stack1.push(node.left);
}
arrayList.add(node.val);
}
index = 1;
}
if(arrayList.size()>0)
list.add(arrayList);
}
return list;
}
}
import java.util.ArrayList;
import java.util.*;
/*
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
ArrayList<ArrayList<Integer> > Print(TreeNode pRoot) {
ArrayList<ArrayList<Integer>> list = new ArrayList<>();
if(pRoot == null)
return list;
LinkedList<TreeNode> queue = new LinkedList<>();
queue.offer(pRoot);
while(!queue.isEmpty()){
int num = queue.size();
ArrayList<Integer> array = new ArrayList<>();
while(num > 0){
TreeNode node = queue.poll();
if(node.left != null)
queue.offer(node.left);
if(node.right != null)
queue.offer(node.right);
array.add(node.val);
-- num;
}
if(array.size() > 0){
list.add(array);
}
}
return list;
}
}
/*
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
int index = 0;
String Serialize(TreeNode root) {
if(root == null)
return "#,";
String res = root.val +",";
res += Serialize(root.left);
res += Serialize(root.right);
return res;
}
TreeNode Deserialize(String str) {
String[] s = str.split(",");
return Deserialize(s);
}
TreeNode Deserialize(String[] s){
if(s[index].equals("#")){
++index;
return null;
}
TreeNode root = new TreeNode(Integer.parseInt(s[index++]));
root.left = Deserialize(s);
root.right = Deserialize(s);
return root;
}
}
/*
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
int index = 0;
TreeNode KthNode(TreeNode pRoot, int k)
{
if(pRoot != null){
TreeNode node = KthNode(pRoot.left,k);//找到中序第一个节点
if(node != null)
return node;
++index;
if(index == k )
return pRoot;
node = KthNode(pRoot.right,k);
if(node != null)
return node;
}
return null;
}
}
import java.util.*;
public class Solution {
int count = 0;
private PriorityQueue<Integer> minHeap = new PriorityQueue<>();
private PriorityQueue<Integer> maxHeap = new PriorityQueue<>(15,new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o2 - o1;
}
});
public void Insert(Integer num) {
if((count & 1) == 0){
if(!maxHeap.isEmpty() && maxHeap.peek() > num) {
maxHeap.offer(num);
num = maxHeap.poll();
}
minHeap.offer(num);
}else {
if(!minHeap.isEmpty() && minHeap.peek() < num){
minHeap.offer(num);
num = minHeap.poll();
}
maxHeap.offer(num);
}
++count;
}
public Double GetMedian() {
if((count & 1) == 1)
return Double.valueOf(minHeap.peek());
else
return Double.valueOf(minHeap.peek() + maxHeap.peek())/ 2;
}
}
import java.util.*;
public class Solution {
public static ArrayList<Integer> maxInWindows(int [] num, int size)
{
ArrayList<Integer> list = new ArrayList<>();
if(num == null ||size == 0 || num.length < size)
return list;
LinkedList<Integer> queue = new LinkedList<>();
for(int i=0; i<num.length; i++){
while(!queue.isEmpty()&& num[i] > num[queue.getLast()])
queue.pollLast();
queue.offerLast(i);
if(i - queue.getFirst() >= size)
queue.pollFirst();
if(i >= size-1)
list.add(num[queue.peek()]);
}
return list;
}
}
public class Solution {
public boolean hasPath(char[] matrix, int rows, int cols, char[] str)
{
int[] flag = new int[matrix.length];
for(int i=0; i<rows; i++){
for(int j=0; j<cols; j++){
if(help(matrix,i,j, rows,cols,str,flag,0))
return true;
}
}
return false;
}
public boolean help(char[] matrix, int i, int j, int rows, int cols, char[] str, int[] flag, int k){
int index = i * cols + j;
if(i<0 || i>=rows || j<0 || j >= cols || flag[index] == 1 || str[k] != matrix[index])
return false;
if(k == str.length-1)
return true;
flag[index] = 1;
if(help(matrix,i-1,j,rows,cols,str,flag,k+1) || help(matrix,i+1,j,rows,cols,str,flag,k+1)
|| help(matrix,i,j-1,rows,cols,str,flag,k+1) ||help(matrix,i,j+1,rows,cols,str,flag,k+1))
return true;
flag[index] = 0;
return false;
}
}
public class Solution {
public int movingCount(int threshold, int rows, int cols)
{
int[][] move = new int[rows][cols];
return moveing(threshold, 0, 0, rows, cols, move);
}
public int moveing(int threshold, int i, int j,int rows, int cols, int[][] move){
if(i < 0 || j <0 || i>=rows || j >= cols || !isCanMove(i,j, threshold) || move[i][j] == 1)
return 0;
move[i][j] = 1;
return moveing(threshold, i+1, j, rows, cols, move)
+moveing(threshold, i-1, j, rows, cols, move)+
moveing(threshold, i, j-1, rows, cols, move)+
moveing(threshold, i, j+1, rows, cols, move)+1;
}
public boolean isCanMove(int rows, int cols, int threshold){
int sum = 0;
while(rows > 0){
sum += rows % 10;
rows = rows/ 10;
}
while(cols >0){
sum += cols % 10;
cols = cols /10;
}
if(sum <= threshold)
return true;
return false;
}
}