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

a)        常规程序,直接遍历二维数组

public class Solution {

    public boolean Find(int [][] array,int target) {

        int flag = 0;

        for(int i = 0; i < array.length; i++){

            int[] arr2 = array[i];

            for(int j = 0; j < arr2.length; j++){

                if(array[i][j] == target){

                    flag = 1;

                }

            }

        }

        if(flag == 1){

            return true;

        } else{

            return false;

        }

    }

    public static void main(String[] args){

        int[][] array = new int[][] { { 1 }, { 2, 3 }, { 4, 5, 6 } };

        Solution s = new Solution();

        System.out.print(s.Find(array, 7));

    }

}

b)        最佳解法,从左下角开始比较,当key值小于数组中的值时向上移,当key值大于数组中的值时向右移。

public class Solution {

       public boolean find(int[][] array, int key){

              int len = array.length - 1;

              int i = 0;

              while((len > 0) && (i < array[0].length)){

                     if(key < array[len][i]){

                            len--;

                     }else if(key > array[len][i]){

                            i++;

                     }else{

                            return true;

                     }

              }

              return false;

       }

       public static void main(String[] args) {

              int[][] array = new int[][]{{1,2,3},{4,5,6},{7,8,9}};

              Solution solution = new Solution();

              System.out.println(solution.find(array, 5));

       }

}

c)        代码最简洁

public boolean Find(int [][] array,int target) {

        for (int[] is : array) {

            for (int i = 0; i < is.length; i++) {

                if (is[i] == target) {

                    return true;

                }

            }

        }

        return false;

}

2.请实现一个函数,将一个字符串中的空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。

a)        我的实现方法,先把StringBuffer转化成一个String字符串,然后遍历字符串,如果存在空格,就替换成“%20”

public class Solution {

       public String replaceSpace(StringBuffer str) {

              String[] s = str.toString().split("");

              String string = "";

              for(int i = 0; i < s.length; i++){

                     if(s[i].equals(" ")){

                            s[i] = "%20";

                     }

                     string = string + s[i];

              }

              return string;

       }

       public static void main(String[] args) {

              Solution solution = new Solution();

              StringBuffer str = new StringBuffer("We Are Happy");

              System.out.println(solution.replaceSpace(str));

       }

}

3.输入一个链表,从尾到头打印链表每个节点的值。

输入描述:

输入为链表的表头

输出描述:

输出为需要打印的“新链表”的表头

import java.util.ArrayList;

public class Solution {

    public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {

        ArrayList<Integer> a = new ArrayList<Integer>();

        ListNode node = listNode;

        while(node != null){

            a.add(new Integer(node.val));

            node = node.next;

        }

        Integer b;

        for(int i = 0; i < a.size()/2; i++){//使用for循环语句把链表的值前后调//换过来

            b=a.get(i);

            a.set(i, a.get(a.size()-i-1)); 

            a.set(a.size()-i-1,b);

        }

        return a;

    }

}

4.输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。

public class Solution {

//根节点类

class TreeNode {

        int val;

        TreeNode left;

        TreeNode right;

        TreeNode(int x) {

               val = x;

        }

}

public TreeNode reConstructBinaryTree(int[] pre, int[] in) {

        // 根节点是前序遍历中的第一个元素

        TreeNode root = new TreeNode(pre[0]);

        // 当只有一个数据时

        int len = pre.length;

        if (len == 1) {

               root.left = null;

               root.right = null;

        }

        // 找到根节点在中序遍历中的位置

        int rootval = root.val;

        int i;

        for (i = 0; i < in.length; i++) {

               if (rootval == in[i]) {

                      break;

               }

        }

        // 创建左子树

        if (i > 0) {

               int[] leftPre = new int[i];

               int[] leftIn = new int[i];

               for (int j = 0; j < i; j++) {

                      leftPre[j] = pre[j+1];

                      leftIn[j] = in[j];

               }

               root.left = reConstructBinaryTree(leftPre, leftIn);

        } else {

               root.left = null;

        }

        // 创建右子树

        if (len - i - 1 > 0) {

               int[] rightPre = new int[len - i - 1];

               int[] rightIn = new int[len - i - 1];

               for (int j = i + 1; j < len; j++) {

                      rightPre[j - i - 1] = pre[j];

                      rightIn[j - i - 1] = in[j];

               }

               root.right = reConstructBinaryTree(rightPre, rightIn);

        } else {

               root.right = null;

        }

        return root;

}

}

5.用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。

public class Solution {

              Stack<Integer> stack1 = new Stack<Integer>();

              Stack<Integer> stack2 = new Stack<Integer>();

              public void push(int node) {

                     stack1.push(node);//这里要进队列就直接进stack1

              }

              public int pop() {

                     int val= 0;

               //把stack1中的内容安倒序放入stack2中

                     while (!stack1.empty()) {

                            stack2.push(stack1.pop());

                     }

                     if (!stack2.empty()) {

                            val = stack2.pop();

                     } else {

                            System.out.println("队列为空,返回默认值0");

                     }

              //实现了出队列 后还要把stack2中的内容还给stack1

                     while (!stack2.empty()) {

                            stack1.push(stack2.pop());

                     }

                     return val;

              }

              public static void main(String[] args) {

                     Solution s = new Solution();

                     s.push(1);

                     s.push(2);

                     s.push(4);

                     System.out.println(s.pop());

                     System.out.println(s.pop());

                     System.out.println(s.pop());

                     System.out.println(s.pop());

              }

}

Java--剑指offer(1)的更多相关文章

  1. 剑指Offer:面试题15——链表中倒数第k个结点(java实现)

    问题描述 输入一个链表,输出该链表中倒数第k个结点.(尾结点是倒数第一个) 结点定义如下: public class ListNode { int val; ListNode next = null; ...

  2. 剑指offer编程题Java实现——面试题5从头到尾打印链表

    题目描述* 剑指offer面试题5:从尾到头打印链表 输入一个链表的头结点,从尾到头打印出每个结点的值 解决方案一:首先遍历链表的节点后打印,典型的"后进先出",可以使用栈来实现这 ...

  3. 剑指offer面试题-Java版-持续更新

    最近在用Java刷剑指offer(第二版)的面试题.书中原题的代码采用C++编写,有些题的初衷是为了考察C++的指针.模板等特性,这些题使用Java编写有些不合适.但多数题还是考察通用的算法.数据结构 ...

  4. 《剑指offer》全部题目-含Java实现

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

  5. 剑指Offer——Java实现栈和队列的互模拟操作

    剑指Offer--Java实现栈和队列的互模拟操作 栈模拟队列   题目:JAVA实现用两个栈来实现一个队列,完成队列的Push和Pop操作.队列中的元素为int类型.   思路:其实就是把队列正常入 ...

  6. 剑指Offer——知识点储备-故障检测、性能调优与Java类加载机制

    剑指Offer--知识点储备-故障检测.性能调优与Java类加载机制 故障检测.性能调优 用什么工具可以查出内存泄露 (1)MerroyAnalyzer:一个功能丰富的java堆转储文件分析工具,可以 ...

  7. 剑指Offer——知识点储备-Java基础

    剑指Offer--知识点储备-Java基础 网址来源: http://www.nowcoder.com/discuss/5949?type=0&order=0&pos=4&pa ...

  8. 剑指offer面试题5 从头到尾打印链表(java)

    注:(1)这里体现了java数据结构与C语言的不同之处 (2)栈的操作直接利用stack进行 package com.xsf.SordForOffer; import java.util.Stack; ...

  9. 剑指offer面试题4 替换空格(java)

    注:利用java中stringBuilder,append,length方法很方便的解决字符串问题 /* * 剑指offer 替换空格 * xsf * */ /*开始替换空格的函数,length为原数 ...

  10. 剑指offer面试题6 重建二叉树(java)

    注:(1)java中树的构建 (2)构建子树时可以直接利用Arrays.copyOfRange(preorder, from, to),这个方法是左开右闭的 package com.xsf.SordF ...

随机推荐

  1. [The Basics of Hacking and Penetration Testing] Learn & Practice

    Remember to consturct your test environment. Kali Linux & Metasploitable2 & Windows XP

  2. 2014 UESTC暑前集训动态规划专题解题报告

    A.爱管闲事 http://www.cnblogs.com/whatbeg/p/3762733.html B.轻音乐同好会 C.温泉旅馆 http://www.cnblogs.com/whatbeg/ ...

  3. Thread对象的yield(),wait(),notify(),notifyall()

    Thread类中的主要方法: join()方法:让一个线程强制运行,线程强制运行期间,其他线程无法运行,必须等到此线程完成之后才可以继续执行. setDaemon():设置线程为后台线程,这样即使Ja ...

  4. [No00003B]string格式的日期时间字符串转为DateTime类型

    新建console程序,复制粘贴直接运行: /**/ //using System.Globalization;//代码测试大致时间2015/11/3 15:09:05 //方法一:Convert.T ...

  5. css3 @font-face设置嵌入字体

    @font-face能够加载服务器端的字体文件,让浏览器端可以显示用户电脑里没有安装的字体

  6. 获取assemblies信息in .net core

    using System; using System.Linq; using System.Reflection; using System.Runtime.Loader; using Microso ...

  7. fMRI数据分析处理原理及方法

    来源: 整理文件的时候翻到的,来源已经找不到了囧感觉写得还是不错,贴在这里保存. 近年来,血氧水平依赖性磁共振脑功能成像(Blood oxygenation level-dependent funct ...

  8. Dynamics CRM 2016 的新特性

    新版本CRM (2016 with update 0.1) 发布已有几个月了,总结一下新特性,从几个方面来看: 1. 针对整合功能的新特性 (1) 增加了CRM App for Outlook. 这个 ...

  9. 【转】加快网站访问速度——Yslow极限优化

    Yslow是一套雅虎的网页评分系统,详细的列出了各项影响网页载入速度的参数,这里不做多说. 我之前就一直参考Yslow做博客优化,经过长时间的学习也算是有所收获,小博的YslowV2分数达到了94分( ...

  10. html文本标准模式,首行空两格,两端对齐,行高

    font-size: 13px; line-height: 1.6; text-align: justify; text-indent: 2em;