剑指offer(41-66)

前言

对于剑指offer中41-66道算法题的解题思路和代码总结。

题目41: 输入一个递增排序的数组和一个数字S,在数组中查找两个数,使得他们的和正好是S,如果有多对数字的和等于S,输出两个数的乘积最小的。
思路
代码
import java.util.ArrayList;
public class Solution {
    public ArrayList<Integer> FindNumbersWithSum(int [] array, int sum) {
        ArrayList<Integer> resList = new ArrayList<>(2);
        if(array == null || array.length < 2)
            return resList;

        int start = 0, end = array.length-1;
        while(start < end){
            int curSum = array[start] + array[end];
            if(curSum == sum){
                resList.add(array[start]);
                resList.add(array[end]);
                break;
            }else if(curSum > sum){
                end--;
            }else{
                start++;
            }
        }

        return resList;
    }
}
题目42: 汇编语言中有一种移位指令叫做循环左移(ROL),现在有个简单的任务,就是用字符串模拟这个指令的运算结果。对于一个给定的字符序列S,请你把其循环左移K位后的序列输出。例如,字符序列S=”abcXYZdef”,要求输出循环左移3位后的结果,即“XYZdefabc”。是不是很简单?OK,搞定它!
思路
代码
public class Solution {
    public String LeftRotateString(String str,int n) {
        if(str == null || str.length() == 0)
            return str;
        int len = str.length();
        int index = n%len;
        if(index == 0)
            return str;
        String str1 = str.substring(0,n);
        String str2 = str.substring(n);
        return str2+str1;
    }
}
题目43: 牛客最近来了一个新员工Fish,每天早晨总是会拿着一本英文杂志,写些句子在本子上。同事Cat对Fish写的内容颇感兴趣,有一天他向Fish借来翻看,但却读不懂它的意思。例如,“student. a am I”。后来才意识到,这家伙原来把句子单词的顺序翻转了,正确的句子应该是“I am a student.”。Cat对一一的翻转这些单词顺序可不在行,你能帮助他么?
思路
代码
import java.util.Stack;
public class Solution {
    public String ReverseSentence(String str) {
        if(str.length() == 0 || str == null)
            return str;
        String[] strs = str.split(" ");
        if(strs.length == 0){
            return str;
        }
        Stack<String> sta = new Stack<>();
        for(String s : strs){
            sta.push(s);
        }
        StringBuffer sb = new StringBuffer();
        while(!sta.empty()){
            sb.append(sta.pop());
            if(!sta.empty())
                sb.append(" ");
        }
        return sb.toString();
    }
}
-->题目44: LL今天心情特别好,因为他去买了一副扑克牌,发现里面居然有2个大王,2个小王(一副牌原本是54张_)...他随机从中抽出了5张牌,想测测自己的手气,看看能不能抽到顺子,如果抽到的话,他决定去买体育彩票,嘿嘿!!“红心A,黑桃3,小王,大王,方片5”,“Oh My God!”不是顺子.....LL不高兴了,他想了想,决定大\小 王可以看成任何数字,并且A看作1,J为11,Q为12,K为13。上面的5张牌就可以变成“1,2,3,4,5”(大小王分别看作2和4),“So Lucky!”。LL决定去买体育彩票啦。 现在,要求你使用这幅牌模拟上面的过程,然后告诉我们LL的运气如何, 如果牌能组成顺子就输出true,否则就输出false。为了方便起见,你可以认为大小王是0。
思路

1、先进行从小打到排序。

2、检测大小王的个数(0)的同时检测是否有重复数字,如果有重复数字,返回false。如果没有重复数字且大小王的个数等于4,返回true。

3、如果大小王个数(0)小于4,用最大的数减去除零以外最小的数,结果小于5则返回true,大于5则返回false。

代码
public class Solution {
    public boolean isContinuous(int [] numbers) {
        if (numbers.length == 0)
            return false;
        Arrays.sort(numbers);
        int wang = 0;
        for (int i = 0; i < numbers.length-1; i++){
            if (numbers[i] == 0){
                wang++;
            }else{
                if (numbers[i+1] == numbers[i])
                    return false;
            }
        }
        if(numbers[numbers.length-1]-numbers[wang] < 5)
            return true;
        return false;
    }
}
题目45:每年六一儿童节,牛客都会准备一些小礼物去看望孤儿院的小朋友,今年亦是如此。HF作为牛客的资深元老,自然也准备了一些小游戏。其中,有个游戏是这样的:首先,让小朋友们围成一个大圈。然后,他随机指定一个数m,让编号为0的小朋友开始报数。每次喊到m-1的那个小朋友要出列唱首歌,然后可以在礼品箱中任意的挑选礼物,并且不再回到圈中,从他的下一个小朋友开始,继续0...m-1报数....这样下去....直到剩下最后一个小朋友,可以不用表演,并且拿到牛客名贵的“名侦探柯南”典藏版(名额有限哦!!_)。请你试着想下,哪个小朋友会得到这份礼品呢?(注:小朋友的编号是从0到n-1),如果没有小朋友,请返回-1
思路
代码
public class Solution {
    public int LastRemaining_Solution(int n, int m) {
        if(n==0||m==0)
            return -1;
        int[] array = new int[n];
        int i = 0, count = n, step = 0;
        while(count > 1){
            if(i == n){
                i = 0;
            }
            if(array[i] == -1){
                i++;
                continue;
            }
            if(step < m-1){
                i++;
                step ++;
            }else{
                array[i] = -1;
                step = 0;
                i++;
                count--;
            }
        }
        int res = 0;
        for(; res < n; res++){
            if(array[res] != -1)
                break;
        }
        return res;
    }
}
-->题目46: 求1+2+3+...+n,要求不能使用乘除法、for、while、if、else、switch、case等关键字及条件判断语句(A?B:C)。
思路

采用短路与的思想,只有&&之前的操作为真时才会执行&&之后的操作,也就是说不满足n>0时,就不再执行递归。

代码
public class Solution {
    public int Sum_Solution(int n) {
        int sum = n;
        boolean a = (n > 0 && (sum += Sum_Solution(n-1)) > 0);
        return sum;
    }
}
-->题目47: 写一个函数,求两个整数之和,要求在函数体内不得使用+、-、*、/四则运算符号。
思路

(1)先用异或计算出不同的二进制位,即相加后不需要进位的二进制表示,再用与计算出相同的二进制位,即相加后需要进位的二进制表示,并向左移动一位。

(2)重复第一步直到与操作计算结果为0,即当前两个二进制表示相加无需再进位,此时两个二进制表示的异或结果即为两数相加的结果。

计算5+4:

5^4 = 101^100 = 1

5&4 = (101&100)<<1 = 1000

1000^0001 = 1001

(1000 & 0001)<<1 = 0

代码
public class Solution {
    public int Add(int num1,int num2) {
        if(num1 = = 0){
            return num2;
        }else if(num2 == 0){
            return num1;
        }

        while(num1 != 0){
            int temp = num1^num2;
            num1 = (num1 & num2)<<1;
            num2 = temp;
        }
        return num2;
    }
}
-->题目48: 将一个字符串转换成一个整数,要求不能使用字符串转换整数的库函数。 数值为0或者字符串不是一个合法的数值则返回0
思路

注意点:边界值,int类型的上下边界为 -231——231-1,即-2147483648——2147483647

正数超过边界时会变成负数,当加到2147483648—>-2147483648,2147483648—>-2147483647.

注意点:1、如果是正数,到累加变成负数时,说明越界

2、如果是负数,-2147483648累加的结果就是-2147483648,当累加值大于-2147483648时,说明越界。

代码
public class Solution {
    public int StrToInt(String str) {
        int len = str.length();
        if(len == 0)
            return 0;
        int sum = 0;
        boolean flag = true;
        for(int i = 0; i < len; i++){
            if(str.charAt(i) == '-') {
                flag = false;
                continue;
            }
            if(str.charAt(i) == '+') {
                flag = true;
                continue;
            }
            if(str.charAt(i) < '0' || str.charAt(i) > '9')
                return 0;
            int h = str.charAt(i) - '0';
            sum = sum*10 + h;
        }
        if(flag == true && sum < 0)
            return 0;
        if(flag == false && sum < 0 && sum > -2147483648)
            return 0;
        return flag == true ? sum : sum*-1;
    }
}
-->题目49: 在一个长度为n的数组里的所有数字都在0到n-1的范围内。 数组中某些数字是重复的,但不知道有几个数字是重复的。也不知道每个数字重复几次。请找出数组中任意一个重复的数字。 例如,如果输入长度为7的数组{2,3,1,0,2,5,3},那么对应的输出是第一个重复的数字2。
思路

因为长度为n的数组中所有数字的范围是0到n-1,从头开始逐一将数组存到对应的数组下标下,如果出现重复存到一个数组下标,说明重复。

代码
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) {
        int i = 0;
        while(i < length){
            if(numbers[i] == i){
                i++;
                continue;
            }
            if(numbers[i] != numbers[numbers[i]]){
                int temp = numbers[i];
                numbers[i] = numbers[temp];
                numbers[temp] = temp;
            }else{
                duplication[0] = numbers[i];
                return true;
            }
        }
        return false;
    }
}
-->题目50:给定一个数组A[0,1,...,n-1],请构建一个数组B[0,1,...,n-1],其中B中的元素B[i]=A[0]A[1]...A[i-1]A[i+1]...A[n-1]。不能使用除法。
思路

先算第一个循环中算出每个元素A[0]A[1]..A[i-1]部分(顺序)

再在第二个循环中乘以A[i+1]A[i+1]...A[n](逆序)

代码
import java.util.ArrayList;
// 时间复杂度高
public class Solution {
    public int[] multiply(int[] A) {
        if(A.length == 0)
            return null;
        int[] res = new int[A.length];
        for(int i = 0; i < A.length; i++){
            int temp = 1;
            for(int j = 0; j < A.length; j++){
                if(i == j){
                    continue;
             
                temp *= A[j];
            }
            res[i] = temp;
        }
        return res;
    }    
}
// 时间复杂度低
public class Solution {
    public int[] multiply(int[] A) {
        if(A.length == 0)
            return null;
        int[] B = new int[A.length];
        B[0] = 1;
        for(int i = 1; i < A.length; i++){
            B[i] = B[i - 1] * A[i - 1];
        }
        int temp = 1;
        for(int i = A.length-2; i >=0; i--){
            temp *= A[i + 1];
            B[i] *= temp;
        }
        return B;
    }
}

-->题目51: 请实现一个函数用来匹配包括'.'和'*'的正则表达式。模式中的字符'.'表示任意一个字符,而'*'表示它前面的字符可以出现任意次(包含0次)。 在本题中,匹配是指字符串的所有字符匹配整个模式。例如,字符串"aaa"与模式"a.a"和"ab*ac*a"匹配,但是与"aa.a"和"ab*a"均不匹配
思路
代码
public class Solution {
     public boolean match(char[] str, char[] pattern)
    {
        if(str.length == 0 && pattern.length == 0)
            return true;
        if(str.length !=0 && pattern.length == 0)
            return false;
        return regular(0, 0, str, pattern);
    }

    public boolean regular(int index1, int index2, char[] str, char[] pattern){
        if(index1 == str.length && index2 == pattern.length)
            return true;
        if(index1 < str.length && index2 == pattern.length)
            return false;
        if(index1 == str.length && index2 < pattern.length){
            if((index2+1)<pattern.length&&pattern[index2+1] == '*'){
                return regular(index1, index2+2, str, pattern);
            }
            return false;
        }

        if(index2+1 < pattern.length && pattern[index2+1] == '*'){
            if(str[index1] == pattern[index2] || pattern[index2] == '.'){
                return regular(index1, index2+2, str, pattern) || regular(index1+1, index2, str, pattern);
            }else{
                return regular(index1, index2+2, str, pattern);
            }
        }
        if(str[index1] == pattern[index2] || (pattern[index2] == '.'))
            return regular(index1+1, index2+1, str, pattern);
        return false;
    }
}
-->题目52: 请实现一个函数用来判断字符串是否表示数值(包括整数和小数)。例如,字符串"+100","5e2","-123","3.1416"和"-1E-16"都表示数值。 但是"12e","1a3.14","1.2.3","+-5"和"12e+4.3"都不是。
思路

需要注意的点:

1、科学计数法中,e或E的前面的数字可以为小数,后面的数组必须是整数。

2、符号必须位于e或E前后的第一位。

3、e或E前面数字的小数点不能出现两次。

代码
public class Solution {
    public boolean isNumeric(char[] str) {
        if(str.length == 0){
            return false;
        }
        return isNumber(0, 0, str);
    }

    public boolean isNumber(int index, int point, char[] str){
        if(index == str.length)
            return true;
        if(point > 1)
            return false;
        if((str[index] == '+' || str[index] == '-')&&index == 0)
            return isNumber(index+1,  point, str);
        if(str[index] == '.')
            return isNumber(index+1, point+1, str);
        if(str[index] >= '0' && str[index] <= '9')
            return isNumber(index+1, point, str);
        if((str[index] == 'e' || str[index] == 'E') && index != str.length-1)
            return isInteger(index+1, 0, str);
        return false;
    }

    public boolean isInteger(int index, int flag, char[] str){
        if(index == str.length)
            return true;
        if(flag > 1 || str[index] == '.')
            return false;
        if(str[index] == '+' || str[index] == '-')
            return isInteger(index+1, flag+1, str);
        if(str[index] >= '0' && str[index] <='9')
            return isInteger(index+1, flag, str);
        return false;
    }
}
题目53: 请实现一个函数用来找出字符流中第一个只出现一次的字符。例如,当从字符流中只读出前两个字符"go"时,第一个只出现一次的字符是"g"。当从该字符流中读出前六个字符“google"时,第一个只出现一次的字符是"l"。
输出描述:
如果当前字符流没有存在出现一次的字符,返回#字符。

思路

代码

import java.util.ArrayList;
import java.util.HashMap;
public class Solution {
    HashMap<Character, Integer> hm = new HashMap<>();
    ArrayList<Character> list = new ArrayList<>();
    //Insert one char from stringstream
    public void Insert(char ch)
    {
        Character cur = (Character) ch;
        if(!hm.containsKey(cur)){
            hm.put(cur, 1);
            list.add(cur);
        }else if(hm.get(cur) == 1){
            hm.put(cur, 2);
            list.remove(cur);
        }
    }
    //return the first appearence once char in current stringstream
    public char FirstAppearingOnce()
    {
        if(list.size()!=0){
            return list.get(0);
        }
        return '#';
    }
}
-->题目54: 给一个链表,若其中包含环,请找出该链表的环的入口结点,否则,输出null。
思路

逐一遍历节点的同时使用HashMap记录遍历过得节点,出现重复时便是环的入口节点。

代码
/*
 public class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}
*/
import java.util.HashMap;
public class Solution {

    public ListNode EntryNodeOfLoop(ListNode pHead)
    {
        
        if(pHead == null)
            return null;
        HashMap<ListNode, Integer> hm = new HashMap();
        while(pHead != null){
            if(!hm.containsKey(pHead)){
                hm.put(pHead, 1);
                pHead = pHead.next;
            }else{
                break;
            }
        }
        if(pHead!=null){
            return pHead;
        }
        return null;
    }
}
-->题目55: 在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点不保留,返回链表头指针。 例如,链表1->2->3->3->4->4->5 处理后为 1->2->5
思路
代码
/*
 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 null;
        ListNode pernode = new ListNode(-1);
        ListNode firNode = pernode;
        pernode.next = pHead;
        int delVal = -1;
        while(pHead != null){
            if(pHead.val == delVal){
                pernode.next = pHead.next;
                pHead = pHead.next;
                continue;
            }
            if (pHead.next != null && pHead.val == pHead.next.val) {
                delVal = pHead.val;
                pernode.next = pHead.next;
                pHead = pHead.next;
                continue;
            }
            pernode = pHead;
            pHead = pHead.next;
        }
        return firNode.next;
    }
}
题目56: 给定一个二叉树和其中的一个结点,请找出中序遍历顺序的下一个结点并且返回。注意,树中的结点不仅包含左右子结点,同时包含指向父结点的指针。
思路

情况1:当前节点有右孩子,然从右孩子开始遍历左孩子,返回最后一个左孩子。

情况2:当前节点无右孩子分为两种情况,一、当前节点是其父节点的左孩子,返回父节点。二、当前节点是其父节点的右孩子,把当前节点指向其父节点,再次判断当前节点是否是其父节点的左孩子,如果不是,重复此过程直到当前节点是其父节点的左孩子为止,如果是,返回父节点。

代码
/*
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;
        }

        if(pNode.right == null){
            while(pNode.next != null){
                if(pNode.next.left == pNode){
                    return pNode.next;
                }
                pNode = pNode.next;
            }
        }
        return null;
    }
}
题目57: 请实现一个函数,用来判断一颗二叉树是不是对称的。注意,如果一个二叉树同此二叉树的镜像是同样的,定义其为对称的。
思路

根节点由左子树A和右子树B,递归判断A的左子树等于B的右子树并且A的右子树等于B的左子树。

代码
/*
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)
    {
        if(pRoot == null)
            return true;
        return hfh(pRoot.left, pRoot.right);
    }

    boolean hfh(TreeNode A, TreeNode B){
        if(A == null && B == null)
            return true;
        if((A !=null && B == null) || (A == null && B != null))
            return false;
        if(A.val == B.val)
            return hfh(A.left, B.right) && hfh(A.right, B.left);
        return false;
    }
}
题目58: 请实现一个函数按照之字形打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右至左的顺序打印,第三行按照从左到右的顺序打印,其他行以此类推。
思路

用一个队列一个栈实现,1、从左到右时使用队列。2、从右到左时先将队列中的元素弹出并压入栈(使其变成倒序),然后再将栈弹出。上面两种操作还需要一个临时队列用于存从队列中弹出的节点的子节点。

代码
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
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) {
        ArrayList<ArrayList<Integer>> als = new ArrayList<>();
        if(pRoot == null)
            return als;
        int h = 1;
        Queue<TreeNode> que = new LinkedList<>();
        Stack<TreeNode> stack = new Stack<>();
        que.add(pRoot);
        while(!que.isEmpty()){
            ArrayList<Integer> res = new ArrayList<>();
            Queue<TreeNode> que2 = new LinkedList<>();
            if(h%2 != 0){
                while(!que.isEmpty()){
                    TreeNode temp = que.poll();
                    if(temp.left != null)
                        que2.add(temp.left);
                    if(temp.right != null)
                        que2.add(temp.right);
                    res.add(temp.val);
                }
            }else{
                while(!que.isEmpty()){
                    TreeNode temp = que.poll();
                    stack.push(temp);
                    if(temp.left != null)
                        que2.add(temp.left);
                    if(temp.right != null)
                        que2.add(temp.right);
                }
                while(!stack.isEmpty()){
                    res.add(stack.pop().val);
                }
            }
            que = que2;
            h++;
            als.add(res);
        }
        return als;
    }
}

public class Sulotion {
    public ArrayList<ArrayList<Integer>> Print(TreeNode pRoot) {
        ArrayList<ArrayList<Integer>> als = new ArrayList<>();
        if(pRoot == null)
            return als;
        int h = 1;
        Queue<TreeNode> tns = new LinkedList<>();
        tns.add(pRoot);
        while (!tns.isEmpty()){
            int size = tns.size();
            ArrayList<Integer> al = new ArrayList<>();
            if (h % 2 == 1){
                for(int i = 0; i < size; i++){
                    TreeNode n = tns.poll();
                    al.add(n.val);
                    if(n.left != null)
                        tns.add(n.left);
                    if (n.right != null)
                        tns.add(n.right);
                }
            }else{
                Stack<TreeNode> s = new Stack<>();
                for(int i = 0; i < size; i++){
                    TreeNode n = tns.poll();
                    s.add(n);
                    if(n.left != null)
                        tns.add(n.left);
                    if (n.right != null)
                        tns.add(n.right);
                }
                while (!s.isEmpty())
                    al.add(s.pop().val);
            }
            als.add(al);
            h++;
        }
        return als;
    }
}
题目59: 从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。
思路
代码
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;


/*
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>> als = new ArrayList<>();
        if(pRoot == null)
            return als;
        Queue<TreeNode> que = new LinkedList();
        que.add(pRoot);
        while(!que.isEmpty()){
            Queue<TreeNode> que2 = new LinkedList<>();
            ArrayList<Integer> al = new ArrayList<>();
            while(!que.isEmpty()){
                TreeNode tn = que.poll();
                al.add(tn.val);
                if(tn.left != null)
                    que2.add(tn.left);
                if(tn.right != null)
                    que2.add(tn.right);
            }
            que = que2;
            als.add(al);
        }
        return als;
    }
    
}

-->题目60:请实现两个函数,分别用来序列化和反序列化二叉树

二叉树的序列化是指:把一棵二叉树按照某种遍历方式的结果以某种格式保存为字符串,从而使得内存中建立起来的二叉树可以持久保存。序列化可以基于先序、中序、后序、层序的二叉树遍历方式来进行修改,序列化的结果是一个字符串,序列化时通过某种符号表示空节点(#),以 !表示一个结点值的结束(value!)。

二叉树的反序列化是指:根据某种遍历顺序得到的序列化字符串结果str,重构二叉树。

思路
代码
/*
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;

    }

}
*/
public class Solution {
    int index = -1;
    String Serialize(TreeNode root) {
        StringBuffer sb = new StringBuffer();
        if(root == null)
            return sb.append("#").toString();
        mySerialize(root, sb);
        return sb.toString();
    }

    public void mySerialize(TreeNode root, StringBuffer sb){
        if(root != null){
            sb.append(root.val + ",");
            mySerialize(root.left, sb);
            mySerialize(root.right, sb);
        }else{
            sb.append("#" + ",");
        }
    }

    TreeNode Deserialize(String str) {
        String[] strs = str.split(",");
        TreeNode root = myDeserialize(strs);
        return root;
    }
    public TreeNode myDeserialize(String[] strs){
        TreeNode root = null;
        index++;
        if(index < strs.length && !strs[index].equals("#")){
            root = new TreeNode(Integer.valueOf(strs[index]));
            root.left = myDeserialize(strs);
            root.right = myDeserialize(strs);
        }
        return root;
    }
}
--> 题目61: 给定一棵二叉搜索树,请找出其中的第k小的结点。例如, (5,3,7,2,4,6,8) 中,按结点数值大小顺序第三小结点的值为4。
思路

二叉搜索树的中序遍历就是从小到大的顺序,利用中序遍历,遍历到第k个返回。

代码
/*
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;

    }

}
*/
public class Solution {
    TreeNode res = null;
    int count = 0;
    TreeNode KthNode(TreeNode pRoot, int k)
    {
        if(pRoot == null){
            return null;
        }
        res(pRoot, k);
        return res;
    }
    
    public void res(TreeNode root, int k){
        if(root == null || res != null)
            return;
        res(root.left, k);
        count++;
        if(count == k){
            res = root;
        }
        res(root.right, k);
    }
}
题目62: 如何得到一个数据流中的中位数?如果从数据流中读出奇数个数值,那么中位数就是所有数值排序之后位于中间的数值。如果从数据流中读出偶数个数值,那么中位数就是所有数值排序之后中间两个数的平均值。我们使用Insert()方法读取数据流,使用GetMedian()方法获取当前读取数据的中位数。
思路

利用小顶堆min存放大的前n/2个数,大顶堆max存放小的后n/2个数,当元素插入时,

min.size()==max.size():q介于max中最大的元素和min中最小的元素,则选择其中一个插入即可。q大于min中最小元素,则插入min。q小于min中最小元素,则插入max。

min.size() > max.size():q大于min中最小的元素,q插入min后再将min中当前最小的元素弹出并插入max。q小于或等于min中最小的元素,则直接插入max。

min.size() < max.size():q小于max中最大的元素,q插入max后再将max中当前最大的元素弹出并插入min。q大于或等于max中最大的元素,则直接插入min。

代码
import java.util.Comparator;
import java.util.PriorityQueue;
public class Solution {
    // 升序
    PriorityQueue<Integer> min = new PriorityQueue<>(20, new Comparator<Integer>() {
        @Override
        public int compare(Integer o1, Integer o2) {
            return o1 - o2;
        }
    });
    // 降序
    PriorityQueue<Integer> max = new PriorityQueue<>(20, new Comparator<Integer>() {
        @Override
        public int compare(Integer o1, Integer o2) {
            return o2 - o1;
        }
    });
    public void Insert(Integer num) {
        if(min.size() == max.size()){
            if(min.size() == 0){
                min.add(num);
            }else{
                if(min.peek() > num){
                    max.add(num);
                }else{
                    min.add(num);
                }
            }
        }else if(min.size() > max.size()){
            if(min.peek() > num){
                max.add(num);
            }else{
                min.add(num);
                max.add(min.poll());
            }
        }else{
            if(max.peek() < num){
                min.add(num);
            }else{
                max.add(num);
                min.add(max.poll());
            }
        }
    }

    public Double GetMedian() {
        if(min.size() == max.size()){
            return (min.peek()+max.peek())*1.0/2;
        }else if(min.size() > max.size()){
            return min.peek()*1.0;
        }else{
            return max.peek()*1.0;
        }
    }
}
-->题目63: 给定一个数组和滑动窗口的大小,找出所有滑动窗口里数值的最大值。例如,如果输入数组{2,3,4,2,6,2,5,1}及滑动窗口的大小3,那么一共存在6个滑动窗口,他们的最大值分别为{4,4,6,6,6,5}; 针对数组{2,3,4,2,6,2,5,1}的滑动窗口有以下6个: {[2,3,4],2,6,2,5,1}, {2,[3,4,2],6,2,5,1}, {2,3,[4,2,6],2,5,1}, {2,3,4,[2,6,2],5,1}, {2,3,4,2,[6,2,5],1}, {2,3,4,2,6,[2,5,1]}。
思路

利用双向链表存储当前最大的值,链表头存的小标始终指向数组中当前窗口的最大元素,后进的元素如果比前面的元素大,则删除前面的元素。

插入2,窗口大小为1。[2]

插入3,前面比3小的元素必然不会是窗口中最大元素,删除2,[2,3],当前窗口大小为2。

插入4,前面比4小的元素必然不会是窗口中最大元素,删除3,[3, 4],当前窗口大小为3==预设窗口大小。提取链表头元素4,{4}

插入2,前面比2大的元素移出窗口后,2有可能成为窗口中最大元素,因此先保留,[4,2],链表尾元素下标-头元素下标不大于预设窗口大小。提取链表头元素4,{4, 4}

插入6,前面比6小的元素必然不会是窗口中最大元素,删除4和2,[4,2,6],链表尾元素下标-头元素下标不大于预设窗口大小。提取链表头元素6,{4,4,6}

插入2,前面比2大的元素移出窗口后,2有可能成为窗口中最大元素,因此先保留,[6,2],链表为元素下标-头元素下标不大于预设窗口大小。提取链表头元素6,{4,4,6,6}

插入5,前面比5小的元素必然不会是窗口中最大元素,删除 2,[6,2,5]。提取链表头元素6,链表尾元素下标-头元素下标不大于预设窗口大小,提取链表头元素6,{4,4,6,6,6}

插入1,前面比1大的元素移出窗口后,1有可能成为窗口中最大元素,因此先保留,链表尾元素下标-头元素下标大于预设窗口大小,删除头元素,[6,5,1],提取链表头元素5,{4,4,6,6,6,5}

代码
import java.util.ArrayList;
import java.util.LinkedList;
public class Solution {
    public ArrayList<Integer> maxInWindows(int [] num, int size)
    {
        ArrayList<Integer> res = new ArrayList<>();
        if(num.length == 0 || size == 0)
            return res;
        LinkedList<Integer> link = new LinkedList<>();
        for(int i = 0; i < num.length; i++){
            while(!link.isEmpty() && num[i] > num[link.peekLast()]){
                link.pollLast();
            }
            link.add(i);
            if((link.peekLast() - link.peek()) >= size)
                link.pop();
            if(i >= size-1)
                res.add(num[link.peek()]);
        }
        return res;
    }
}
-->题目64: 请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。路径可以从矩阵中的任意一个格子开始,每一步可以在矩阵中向左,向右,向上,向下移动一个格子。如果一条路径经过了矩阵中的某一个格子,则该路径不能再进入该格子。 例如{abce sfcs adee}矩阵中包含一条字符串"bcced"的路径,但是矩阵中不包含"abcb"路径,因为字符串的第一个字符b占据了矩阵中的第一行第二个格子之后,路径不能再次进入该格子。
思路
代码
public class Solution {
    public boolean hasPath(char[] matrix, int rows, int cols, char[] str)
    {
        if(rows <= 0 || cols <= 0 || matrix.length == 0 || str.length == 0)
            return false;
        boolean[] visited = new boolean[rows*cols];
        for(int i = 0; i < rows; i++){
            for(int j = 0; j < cols; j++){
                if(myHashPath(matrix, str, 0, i, j, rows, cols, visited))
                    return true;
            }
        }
        return false;
    }

    public boolean myHashPath(char[] matrix, char[] str, int indexStr, int indexRows, int indexCols, int rows, int cols, boolean[] visited){
        boolean flag = false;
        if(indexRows >=0 && indexRows < rows && indexCols >= 0 && indexCols < cols && visited[indexRows*cols+indexCols]!=true && str[indexStr] == matrix[indexRows*cols+indexCols]){
            visited[indexRows*cols+indexCols] = true;
            if(indexStr == str.length-1)
                return true;
            flag = myHashPath(matrix, str, indexStr+1, indexRows-1, indexCols, rows, cols, visited)||
                    myHashPath(matrix, str, indexStr+1, indexRows+1, indexCols, rows, cols, visited)||
                    myHashPath(matrix, str, indexStr+1, indexRows, indexCols-1, rows, cols, visited)||
                    myHashPath(matrix, str, indexStr+1, indexRows, indexCols+1, rows, cols, visited);
            if(!flag){
                indexStr--;
                visited[indexRows*cols+indexCols] = false;
            }
        }
        return flag;
    }


}
-->题目65: 地上有一个m行和n列的方格。一个机器人从坐标0,0的格子开始移动,每一次只能向左,右,上,下四个方向移动一格,但是不能进入行坐标和列坐标的数位之和大于k的格子。 例如,当k为18时,机器人能够进入方格(35,37),因为3+5+3+7 = 18。但是,它不能进入方格(35,38),因为3+5+3+8 = 19。请问该机器人能够达到多少个格子?
思路
代码
public class Solution {
    public int movingCount(int threshold, int rows, int cols)
    {
        if(rows < 0 || cols < 0 || threshold < 0){
            return 0;
        }
        boolean[] visited = new boolean[rows*cols];
        return myCount(threshold, rows, cols, 0, 0, visited);
    }

    public int myCount(int threshold, int rows, int cols, int indexRow, int indexCol, boolean[] visited){
        int index = indexRow*cols + indexCol;
        if(indexRow < 0 || indexRow >= rows || indexCol < 0 || indexCol >= cols || visited[index]==true || !check(indexRow, indexCol, threshold)){
            return 0;
        }
        visited[index] = true;
        return 1 + myCount(threshold, rows, cols, indexRow+1, indexCol, visited)
                + myCount(threshold, rows, cols, indexRow-1, indexCol, visited)
                + myCount(threshold, rows, cols, indexRow, indexCol-1, visited)
                + myCount(threshold, rows, cols, indexRow, indexCol+1, visited);
    }

    public boolean check(int indexRow, int indexCol, int threshold){
        int sum = 0;
        while(indexRow!=0){
            sum += indexRow%10;
            indexRow /= 10;
        }
        while(indexCol!=0){
            sum += indexCol%10;
            indexCol /= 10;
        }
        if(sum > threshold)
            return false;
        return true;
    }
}
--> 题目66: 给你一根长度为n的绳子,请把绳子剪成整数长的m段(m、n都是整数,n>1并且m>1),每段绳子的长度记为k[0],k[1],...,k[m]。请问k[0]xk[1]x...xk[m]可能的最大乘积是多少?例如,当绳子的长度是8时,我们把它剪成长度分别为2、3、3的三段,此时得到的最大乘积是18。
思路

动态规划问题:将大问题细化为小问题 ,然后将所有小问题组合成来解决大问题,如果要返回10的最大乘积

1:无法在分割——1

2:可以分割一次——1

3:可以分割为1、1、1和1、2两种情况,最大乘积为后者2.

所有1,2和3是不可在分割最小单位,因为分割之后乘积还没本身大。

4:1,3和2,2,最大乘积为4

5:1,4和2,3,最大乘积为6

6:1,5、2,4和3,3,最大乘积为9

7:1,6、2,5和3,4,最大乘积为12

8:1,7、2,6、3,5和4,4,最大乘积为18

9:1,8、2,7、3,6和4,5,最大乘积为27

10:1,9、2,8、3,7、4,6和5,5,最大乘积为36

解题过程是从前往后的或称,即小解决1,2,3的最大乘积问题,当4出现时,可分为1,3和2,2,这时3,2的最大乘积已经知道,就可以直接拿来用。当5出现时,可分为1,4、2,3,这时1,2,3,4的最大乘积都已知道,只要直接用即可,以此类推。

代码
public class Solution {
    public int cutRope(int target) {
        if(target <= 2){
            return 1;
        }
        if(target == 3){
            return 2;
        }
        int[] product = new int[target + 1];
        product[1] = 1;
        product[2] = 2;
        product[3] = 3;
        for(int i = 4; i <= target; i++){
            int max = 0;
            for(int j = 1; j <= i/2; j++){
                int cur = product[j] * product[i - j];
                if(cur > max)
                    max = cur;
            }
            product[i] = max;
        }
        return product[target];
    }
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容