剑指Offer算法题笔记(第二期)

反转链表

题目

  • 输入一个链表,反转链表后,输出新链表的表头。

思路

  • 把preNode当做是null,将head.next先保存下来,然后将head指向preNode。然后依次前进一格,即head变成nextNode,preNode变成head。值得注意的是,head=null的时候说明已经全部反转完毕,但是头不是head,而是head还没有被复制为null的时候。

AC代码

/*
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||head.next == null)
            return head;
        ListNode preNode = null;
        ListNode resNode = null;
        while(head!=null){
            ListNode nextNode = head.next;
            if(nextNode == null)
                resNode = head;
            head.next = preNode;
            preNode = head;
            head = nextNode;
        }
        return resNode;
    }
}

合并两个排序的链表

题目

  • 输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。

AC代码

  • 递归版本,典型的分治法思路。

      public class Solution {
          public ListNode Merge(ListNode list1,ListNode list2) {
              if(list1==null)
                  return list2;
              if(list2==null)
                  return list1;
              ListNode head = null;
              if(list1.val<list2.val){
                  head = list1;
                  head.next = Merge(list1.next,list2);
              }
              if(list1.val>=list2.val){
                  head = list2;
                  head.next = Merge(list1,list2.next);
              }
              return head;
          }
      }
    
  • 非递归版本,本质上是新建一个头结点然后在头结点上根据元素大小增加节点。值得注意的是,当list1或者list2为null时,while循环会结束,这只能代表为null的那个链表已经完全被添加到新链表中,但是不为null的那个可能还没有添加进去。注意返回值,一开始就要备份头节点、

      public class Solution {
          public ListNode Merge(ListNode list1,ListNode list2) {
              if(list1==null)
                  return list2;
              if(list2==null)
                  return list1;
              ListNode mergeHead = new ListNode(-1);
              ListNode newHead = mergeHead;
              
              while(list1!=null&&list2!=null){
                  if(list1.val < list2.val){
                      mergeHead.next = list1;
                      list1 = list1.next;
                  }
                  else{
                      mergeHead.next = list2;
                      list2 = list2.next;
                  }
                  mergeHead = mergeHead.next;
              }
              if(list1!=null) mergeHead.next = list1;
              if(list2!=null) mergeHead.next = list2;
              return newHead.next;
    
          }
      }
    

树的子结构

题目

  • 输入两棵二叉树A,B,判断B是不是A的子结构。(ps:我们约定空树不是任意一个树的子结构)

思路

  • HasSubtree思路为:先找到root节点相同的,然后比较左右子树(这个过程通过helper完成)。如果root节点相同,但是左右子树比较出的结果是false,那么就需要向下继续遍历root1,看看是否有根节点相同的。helper的思路是,如果root2被遍历完,说明是子结构。如果root2还没遍历完,但是root1遍历完了,那说明root1太短了,因此false,如果root1和root2中有数据不一样,那么仍然是false。返回的结果是左右子树的&&。

AC代码

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

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

    }

}
*/
public class Solution {
    private boolean helper(TreeNode root1,TreeNode root2){
        if(root2==null)
            return true;
        if(root1==null)
            return false;
        if(root1.val != root2.val)
            return false;
        
        return helper(root1.left,root2.left)&&helper(root1.right,root2.right);
    }
    public boolean HasSubtree(TreeNode root1,TreeNode root2) {
        boolean result = false;
        if(root1!=null&&root2!=null){
            if(root1.val==root2.val){
                result = helper(root1,root2);
            }
            if(!result){
                result = HasSubtree(root1.left,root2);
            }
            if(!result){
                result = HasSubtree(root1.right,root2);
            }
        }
        return result;

    }
}

包含min函数的栈

题目

  • 定义栈的数据结构,请在该类型中实现一个能够得到栈中所含最小元素的min函数(时间复杂度应为O(1))。

思路

  • 辅助栈的大小始终和原栈保持一致。min方法实际是查看helper栈顶元素。

    • 原栈 5(最后入栈) 3 3 8 9 8(最先入栈)
    • 辅助 3(最后入栈) 3 3 8 8 8(最先入栈)

    原栈弹出5,辅助弹出3,原栈弹出3,辅助弹出3.
    此时

    • 原栈 3 8 9 8
    • 辅助栈 3 8 8 8

    发现辅助栈中栈头为3,确实是最小的。

AC代码

import java.util.Stack;

public class Solution {
    Stack<Integer> stack = new Stack();
    Stack<Integer> helpStack = new Stack();
    int min = Integer.MAX_VALUE;
    public void push(int node) {
        stack.push(node);
        if(node <= min){
            helpStack.push(node);
            min = node;
        }    
        else
            helpStack.push(min);
            
    }
    
    public void pop() {
        stack.pop();
        helpStack.pop();
    }
    
    public int top() {
        return stack.peek();
    }
    
    public int min() {
        return helpStack.peek();
    }
}

栈的压入、弹出序列

题目:

  • 输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否可能为该栈的弹出顺序。假设压入栈的所有数字均不相等。例如序列1,2,3,4,5是某栈的压入顺序,序列4,5,3,2,1是该压栈序列对应的一个弹出序列,但4,3,5,1,2就不可能是该压栈序列的弹出序列。(注意:这两个序列的长度是相等的)

思路:

  • 采用一个辅助栈的方式。如果辅助栈顶和弹出栈值相同,则一起弹出,否则辅助栈一直入栈。两个序列按此操作,全部填满后一起弹出,如果弹出时有不同元素则false,一起弹出至空,为true。

AC代码

import java.util.ArrayList;
import java.util.Stack;


public class Solution {
    public boolean IsPopOrder(int [] pushA,int [] popA) {
        Stack<Integer> helpStack = new Stack();
        for(int i=0;i<popA.length;i++){
            helpStack.push(popA[i]);
        }
        Stack<Integer> stack = new Stack();
        for(int i=0;i<pushA.length;i++){
            stack.push(pushA[i]);
            if(helpStack.peek()==stack.peek()){
                helpStack.pop();stack.pop();
            }
        }
        while(!helpStack.isEmpty()||!stack.isEmpty()){
            if(helpStack.peek()!=stack.peek()){
                return false;
            }else{
                helpStack.pop();stack.pop();
            }
        }
        return true;

    }
}

二叉搜索树的后序遍历序列

题目

  • 输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历的结果。如果是则输出Yes,否则输出No。假设输入的数组的任意两个数字都互不相同。

思路

  • 以数组末尾为root切分,比root小的必然是root的左子树,比root大的必然是root的右子树。如果切分后,发现双指针没有相遇,说明不符合BST的要求,必然为false。值得注意的是,java中不能写成while(i<=end&&array[i++]<root);会有问题。要写成while(i<=end&&array[i]<root) i++;还有要注意的,要小心end前面的数组是单调递增或者递减,在while中要判断越界。

AC代码

public class Solution {
    private boolean helper(int [] array,int start,int end){
        if(start >= end)
            return true;
        int root = array[end];
        int i = start;
        int j = end-1;
        while(i<=end&&array[i]<root) i++;
        i--;
        while(j>=0&&array[j]>root) j--;
        j++;
        if(j-i!=1)
            return false;
        return helper(array,start,i) && helper(array,j,end-1);     
    }
    
    public boolean VerifySquenceOfBST(int [] sequence) {
        int end = sequence.length-1;
        if(end==-1)
            return false;
        return helper(sequence,0,end);
    }
}

二叉树中和为某一值的路径

题目

  • 输入一颗二叉树的跟节点和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。(注意: 在返回值的list中,数组长度大的数组靠前)

思路

  • 类似前序遍历的去查一棵树。为什么要前序遍历呢?因为只有前序遍历是率先访问根节点。递归汇总为什么访问完左右子树之后要remove呢?是因为树的递归回去的时候,path中应该去掉当前节点的值。

AC代码

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 void helper(TreeNode root,int target,ArrayList<Integer> path,ArrayList<ArrayList<Integer>> res){
        if(root==null)
            return;
        path.add(root.val);
        if(target==root.val&&root.left==null&&root.right==null){
            res.add(new ArrayList(path));
        }else{
            helper(root.left,target-root.val,path,res);
            helper(root.right,target-root.val,path,res);
        }
        path.remove(path.size()-1);
        
    }
    
    public ArrayList<ArrayList<Integer>> FindPath(TreeNode root,int target) {
        ArrayList<Integer> path = new ArrayList();
        ArrayList<ArrayList<Integer>> res = new ArrayList();
        helper(root,target,path,res);
        return res;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值