剑指offer(java代码版)

本文章转载之:https://www.cnblogs.com/ysw-go/p/6272551.html

1,singleTon实例
题目描述:设计一个类,我们只能生成该类的一个实例
//volatile:防止指令重排序
public class singletonClass{

private static volitile singletonClass instance;

private singletonClass(){

}

public static singletonClass getInstance(){

if(instance==null){
   synchronized(singletonClass.class){
      if(instance==null){
      instance = new singletonClass();
} 
}   
return instance;

}
}
}

2,二位数组中的查找
在一个二位数组中,每一行都按照从左到右递增的顺序排列,每一列都按照从上到下的顺序排序,完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否包含该整数

public class find(){

public static boolean find(int arr[][],int keyNumber){

 int column =arr[0].length-1;
 int row = 0;
 while(column>0&&row<arr.length){
   if(arr[row][column]==keyNumber){
       return true;
   }  
  else if(arr[arr][column]>keyNumber){
      column--;
   } 
  else{
     row++;
   }         
 }

}
return false;
}
//测试find函数
public static void main(String args[]){
//测试这个数组
/*
* 1 2 8 9
* 2 4 9 12
* 4 7 10 13
* 6 8 11 15
*/
int array[][] = new int[4][4];
array[0][0]=1;
array[0][1]=2;
array[0][2]=8;
array[0][3]=9;
array[1][0]=2;
array[1][1]=4;
array[1][2]=9;
array[1][3]=12;
array[2][0]=4;
array[2][1]=7;
array[2][2]=10;
array[2][3]=13;
array[3][0]=6;
array[3][1]=8;
array[3][2]=11;
array[3][3]=15;
System.out.println(find(array,7));
System.out.println(find(array,5));
}

3,空格替换
题目描述: 请实现一个函数,将字符串的每个空格替换为"%20"。
例如输入"We are happy",则输出"We%20are%20happy."。

public class replaceBlank{

public String replace(String input){

StringBuilder build = new StringBuilder();
if(input==null||input.length()==0){
  return null;
}
for(int i=0;i<input.length();i++){
  
   if(input.charAt(i)==' '){
     builder.append("%");
     builder.append("2");
     builder.append("0");
   }else{
    builder.append(input.charAt(i));
   }
}
return builder.toString(); 

}
}

//测试用例
public static void main(String[] args){
ReplaceBlank test = new ReplaceBlank();

String str1=“We are happy”
System.out.println(test.replace(str1));

}

4,从尾到头打印链表
题目描述:输入一个链表的头结点,从头到尾反过来打印每个结点的值

//首先定义链表结构
class LinkNode{
LinkNode next;
int node_value;
}

public class PrintListReverse{
public void reverse(LinkNode headNode){
//用栈的思想来实现链表的倒叙输出
Stack stack = new Stack();
while(headNode!=null){
stack.push(headNode);
headNode = headNode.next;
}
while(!stack.isEmpty()){
System.out.println(stack.pop().node_value+"");
}
System.out.print();
}

public static void main(String[] args){

PrintListReverse plr = new PrintReverse();
LinkNode node1 = new LinkNode();
LinkNode node2 = new LinkNode();
LinkNode node3 = new LinkNode();

node1.next_value=1;
node2.next_value=2;
node3.next_value=3;

node1.next=node2;
node2.next=node3;
plr.reverse(node1);
}

}

4,题目描述:输入某二叉树的前序遍历和中序遍历结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不包含重复的数字。例如输入前序遍历序列:{1,2,4,7,3,5,6,8}和中序遍历{4,7,2,1,5,3,8,6},则重建出图中所示二叉树并且输出它的头结点。

重建的二叉树:

//定义二叉树节点
class BinaryTreeNode{
public int value;
public BinaryTreeNode leftNode;
public BinaryTreeNode rightNode;

//无参构造函数
public BinaryTreeNode{

}

//定义有参的构造函数
public BinaryTreeNode(int value){
this.value = value;
this.leftNode = null;
this.rightNode = null;
}
}

//构造二叉树
public Class ConstructBinaryTree{

public static BinaryTreeNode construct(int preOrder{},int inOrder{},int length) throws Exception{
   
  if(preOrder ==null||inOrder==null||length<0){
    return null;
  }
  return constructCore(preOrder,0,preOrder.length-1,inOrder,0,inOrder.length - 1);      
}

public static BinaryTreeNode constructCore(int preOrder{},
int startPreIndex, int endPreIndex, int inOrder{},
int startInIndex,int endInIndex)throws InvalidPutException{

//头结点的值
int rootValue = preOrder[startInIndex];

//构建一个只有一个根节点的二叉树
BinaryTreeNode root  = new BinaryTreeNode(rootValue);

//只有一个元素的情况下
if(startPreIndex == endPreIndex){
   if(startInIndex == endInIndex
    && preOrder[startInIndex] == inOrder[endInIndex]){
     System.out.println("只有一个元素");
     return root;
    }else{
      throw new InvalidPutException();
    }
 }

//最重要的一步:在中序遍历中找到根结点的索引
int rootInIndex = startInIndex;
while(rootInIndex<=endInIndex && inOrder[rootInIndex]!=rootValue){
     rootInIndex++;
}
if(rootInIndex == endInIndex && inOrder[rootInIndex]!=rootValue){
   throw new InvalidPutException();
}

//根结点的左子数的长度
int leftLength = rootInIndex - startInIndex;
//根节点的左子数的最右端的索引值
int leftPreEndIndex = startPreIndex + leftLength;    
//构建左子树
if(leftLength>0){
 root.leftNode = constructCore(preOrder,startPreIndex + 1,
    leftPreEndIndex, inOrder,startInIndex,rootInIndex - 1);
}
//说明根结点存在右子数
if(leftLength < endPreIndex - startPreIndex){
   root.rightNode = constructCore(preOrder,leftPreEndIndex+1,
   endPreIndex,inOrder,rootInIndex+1,endInIndex);
}     
return root;

}

//按照前序遍历打印二叉树的节点
public static void printPreBinaryTree(BinaryTreeNode root){
if(root ==null){
return;
}else{
System.out.println(root.value+"");
}

if(root.leftNode!=null){
 printPreBinaryTree(root.rightNode);
}
if(root.rightNode!=null){
 printPreBinaryTree(root.rightNode);
}

}

public static class InvalidPutException extends Exception {

      private static final long serialVersionUID = 1L;
}

public static void main(String[] args) throws Exception{
int preOrder[] = {1,2,4,7,3,5,6,8};
int inOrder[] = {4,7,2,1,5,3,8,6};
ConstructBinaryTree test = new ConstructBinaryTree();
printPreBinaryTree(test.construct(preOrder,inOrder,preOrder.length));
}

}

6,用两个栈实现队列
题目描述:用两个栈实现一个队列。队列的声明如下,请实现它的两个函数appendTail和deleteHead,分别完成在队列尾部插入结点和在队列头部删除结点的功能。

public class constractQueue{

Stack stack1 = new Stack();
Stack stack2 = new Stack();

public void appendTail(int a){
stack1.push(a);
}

public void deleteHead() Throws Exception{
if(stack2.isEmpty){
if(!stack1.isEmpty){
stack2.push(stack1.pop());
}
}
if(stack2.isEmpty){
System.out.println(“队列为空不能删除”);
}
return stack2.pop();
}

public static void main(String args[]){

ConstractQueue test = new ConstractQueue();
//向空的队列中添加元素,删除元素
test.append(“1”);
System.out.println(test.deleteHead());
}
}

7,旋转数组的最小数字
题目描述:把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。输入一个递增排序的数组的一个旋转,输出旋转数组的最小元素。例如数组{3,4,5,1,2}为{1,2,3,4,5}的一个旋转,该数组的最小值为1;
public class MinInReversingList{

public static int minElement(int array[]) throws Exception{

   //条判断
  if(array==null||array.length<=0){
    throw new Exception(Invalid parameters);
   }

  int left = 0;
  int right = array.length-1;
  int mid = left;
  while(array[left]>=array[right]){
    //跳出循环的条件
    if(right-left==1){
     mid = right;
     break;
     }
     mid = (left + right)/2;
     if(array[left]==array[mid] && array[mid] == array[right]){
         return minFromSortSearch(array);
      }else{
         //算法的核心思想
        if(array[mid]>array[left]){
          left = mid;
        }
        if(array[mid]<=array[right]){
         right = mid
        }
      }            
  }
   return array[right];

}
}
8,斐波那契数列
题目描述:写一个函数,输入n,求斐波那契数列的第n项,斐波那契数列的定义如下: n=0,f(n)=0 ;n=1,f(n)=1 n>1;f(n)=f(n-1)+f(n-2).
青蛙跳台阶的问题,也可以用裴波那契数列
package Fibonacci;

public class Fibonacci {

 public static long Fib2(int n) {
	       long FibOne = 0;
	       long FibTwo = 1;
	       long FibN = 0;
	       int result[] = { 0,1 };
	       if (n < 2) {
	           return result[n];
	       } else {
	           for (int i = 2; i <= n; i++) {
	               FibN = FibTwo + FibOne;
	               FibOne = FibTwo;
	               FibTwo = FibN;
	           }
	       }
	       return FibN;
	   }
	
	   public static void main(String[] args) {
	       // 用解法1求序列的第100项,直接不动了
	       // System.out.println(Fib1(100));
	       System.out.println(Fib2(2));
	   }

}
9,问题描述: 请实现一个函数,输入一个整数,输出该数二进制表示中1的个数。例如把9表示成二进制是1001,有2位是1 因此如果输入9,该函数输出2;
public class NumbleOf1{

public int numble(int n ){
int count = 0;
int flag = 1;
while(flag!=0){
if((n&flag)!=0){
count++;
}
flag= flag<<1;
}
return count;
}

public static void main(String args){
NumbleOf1 test = new NumbleOf1();
System.out.println(test.numble(9));
}

}

10,问题描述:实现函数double power(double base,int exponent),求base的exponent次方。不能使用库函数,同时不需要考虑大数问题。

public class Power{

public double power(double base,int export){
double result = 0.0;
if(equal(base,0)&& export0){
System.out.println(“0的负数次幂没有意义”);
}
if(export
0){
return result = 1.0;
}
if(export<0){
return unsignPower(base,-export);
}else{
return unsignPower(base,export);
}
return result;
}

public double unsignPower(double base,int export){
double result = 1.0;
for(int i=0;i<export;i++){
result = result * base;
}
return result;
}

//由于计算机有限的保留位数,因此当一个数与0相差0.000001时,默认为0,
public boolean equal(double numble1,double numble2){
if((numble1 - numble2>-0.000001)&&(numble1 - numble2<0.000001)){
return ture;
}
return false;
}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值