剑指offer读书笔记(2)

来源:互联网 发布:电力系统短路计算软件 编辑:程序博客网 时间:2024/05/16 19:05

1、给定一个double类型的浮点数base和int类型的整数exponent。求base的exponent次方。

public class Solution {    public double Power(double base, int exponent) {       if(exponent==0)        return 1;    double rest=1.0d;        for(int i=0;i<Math.abs(exponent);i++){            rest=rest*base;        }        if(exponent>0)        return rest;        else return 1/rest;}}

2、输入一个整数数组,实现一个函数来调整该数组中数字的顺序,使得所有的奇数位于数组的前半部分,所有的偶数位于位于数组的后半部分,并保证奇数和奇数,偶数和偶数之间的相对位置不变。

public class Solution {    public void reOrderArray(int [] array) {      for(int i=0;i<array.length-1;i++){          for(int j=0;j<array.length-1-i;j++){              if(array[j]%2==0&&array[j+1]%2==1){                  int t=array[j];                  array[j]=array[j+1];                  array[j+1]=t;              }          }      }    }}
3、输入一个链表,输出该链表中倒数第k个结点。

public class Solution {    public ListNode FindKthToTail(ListNode head,int k) {if(head==null||k==0)                return null;        ListNode p=head;        ListNode q=null;        for(int i=0;i<k-1;i++){            if(p.next!=null)            {p=p.next;}            else{                return null;            }        }        q=head;        while(p.next!=null){            p=p.next;            q=q.next;        }        return q;    }}
4、输入一个链表,反转链表后,输出链表的所有元素。

public class Solution {    public ListNode ReverseList(ListNode head) {if(head==null)    return null;        ListNode end =null,p,q;        p=head;         while(p!=null){             q=p.next;             p.next=end;             end=p;             p=q;         }         return head;    }}
5、输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。

public class Solution {    public ListNode Merge(ListNode list1,ListNode list2) {        if(list1==null){    return list2;    }    else if(list2==null){    return list1;    }    ListNode p=null;    if(list1.val<list2.val)    {    p=list1;                    p.next=Merge(list1.next,list2);        }        else{                    p=list2;                    p.next=Merge(list1,list2.next);                }    return p;        }        }

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

public class Solution {    public boolean HasSubtree(TreeNode root1,TreeNode root2) {        if(root2==null)            return false;       else if(root1==null&root2!=null)           return false;      return issun(root1,root2)||HasSubtree(root1.left,root2)|| HasSubtree(root1.right,root2);}    public boolean issun(TreeNode root1,TreeNode root2){if(root2==null)    return true;        if(root1==null){            return false;        }        if(root1.val!=root2.val)            return false;        return issun(root1.left,root2.left)&&issun(root1.right, root2.right);    }    }




0 0
原创粉丝点击