Sword finger offer1-7 questions

Keywords: Java Programming

/**

  • In a two-dimensional array (the length of each one-dimensional array is the same), each row is sorted in ascending order from left to right, and each column is sorted in ascending order from top to bottom. Please complete a function, input such a two-dimensional array and an integer to determine whether the array contains the integer.
    Train of thought:
    Select a dimension (row or column) to find the row (column) of the element to be found, and then find the specific column (row) location of the element from the row (column). Complexity O(n).

Optimization: because the sequence is incremental and orderly, binary search can be carried out for optimization, but this problem can be done without binary. Because you are interested in looking up how large the programming language array can be. Then individual lookups in this range do not time out even if they are not optimized. If you are interested, you can write it yourself! Complexity O(logn)
*/

public class Shuzuchazhao {


       public boolean Find(int target,int [][] array){
           if (array.length==0||array[0].length==0)
               return false;
           for (int i=array.length-1;i>=0;i--){
               if (array[i][0]>target){
                   continue;
               }
               for (int j=0;j<array[0].length;j++){
                    if (array[i][j] == target){
                        return true;
                    }
               }
           }
           return false;
       }
}

/**

  • Please implement a function to replace each space in a string with "% 20". For example, when the string is We Are Happy, the replaced string is We%20Are%20Happy.
  • String traversal and reconstruction. Encountered for the character directly in the new character to add a% 20. Of course, you can use replaceAll directly in java. Complexity O(n);
  • PS: the efficiency of replaceall is low. It is recommended to use StringBuider or the like to complete
  • There is a discussion about whether to move the original String or create a new String. Of course, it's easier to create a new String, but if you need to move based on the original String, because the underlying implementation of String is array, you need to traverse it once to know how many spaces there are, and then expand the space. As for the moving mode after traversing the space: it's better to move from the back to the front, because the final moving position is the same, but every time you encounter a space from the front to the back, you will drag your family behind you and a String will follow you. (for example, when the line of speech under the national flag falls back, it needs to be lowered many times and moves slowly as a whole), and when you insert it from the back to the front, it means that you know exactly where to move one by one.
  • Although the total distance between the two words is the same, each word from the front to the back can only move to the end after (1-n) times, and each word from the back to the front can only move to the target position once!
    */
public class Tihuankongge {
       /** public static String replaceSpace(StringBuffer str){
            String team = str.toString();
            return team.replaceAll(" ","%20");
        }
        **/
        public static String  replaceSpace(StringBuffer str){
            StringBuffer str2=new StringBuffer();
             char demo=' ';
             for (int i=0;i<str.length();i++){
                 demo=str.charAt(i);
                 if (demo == ' '){
                     str2.append("%20");
                 }
                 else {
                     str2.append(demo);
                 }
             }
             return str2.toString();
        }
}

/**

  • Enter a linked list and return an ArrayList from the end to the end of the list.
  • Train of thought:
  • The title gives us a List of links that let us return a sequence number. This sequence requires us to return the List from the back to the front. Of course, there are many ways to deal with it. For example, you can store an array from the beginning to the end, and then the array can be stuffed into the List from the end to the end.
  • Of course, Arraylist itself is also a linear table (sequence table), which can be used for header insertion. Insert the number of each backward traversal of the list in the first place, and then return.
    */
public class Linkedlist {
    public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {

        ArrayList<Integer>list=new ArrayList<Integer>();
        while (listNode!=null) {
            list.add(0, listNode.val);
            listNode=listNode.next;
        }
        return list;

    }
}

/**

  • Enter the results of the preorder traversal and inorder traversal of a binary tree, and rebuild the binary tree. It is assumed that the results of the input preorder traversal and preorder traversal do not contain duplicate numbers. For example, if the sequence {1,2,4,7,3,5,6,8} and the sequence {4,7,2,1,5,3,8,6} are input, the binary tree will be reconstructed and returned.
  • We all know that a middle order sequence with a pre order or a post order sequence can determine a complete binary tree. First of all, this kind of problem is analyzed. Most of the problems of binary trees are repeatable, and recursion is often used. So most people should be able to think about using recursion, but it may not be clear how to do it. In fact, the use of recursion does not require you to consider the whole article, you need to consider one of the processes carefully and completely. Now let's look at the construction process of preorder ergodic sequence {1,2,4,7,3,5,6,8} and mesorder ergodic sequence {4,7,2,1,5,3,8,6}!
  • For the preamble, we know from root or not, so we can be sure that the first one is root. However, the middle order is left middle right. If we find the position of the root, then we can make sure that the left side of the root is the left side, and the right side of the root is the right side of the binary tree.
    
  • However, it is important to note that the left side of the middle order and the right side of the middle order are the left side and the right side of the front order. Although the specific sorting may be different, the left region and the right region (the total number of regional elements) are also continuous, so we can determine the only root in this way, and then there are left and right regions in the front order, and left and right regions in the middle order. In this way, we can recursively construct the subtree to complete the binary sorting tree.
    
  • So, if it is implemented by code, the more troublesome thing is to consider the interval of the array, and record the left and right intervals of the two arrays to be recovered.
    

*/

public class Binarytree {

      public TreeNode reConstructBinaryTree(int [] pre, int [] in){
            TreeNode node=new TreeNode(in[0]);
            int preleft=0,preright=pre.length-1;
            int inleft=0,inright=pre.length-1;
            return creat(pre,in,preleft,preright,inleft,inright);
      }
      private TreeNode creat(int[] pre,int[] in,int preleft,int preright,int inleft,int inright){
            if (preleft>preright||inleft>inright) return null;
            TreeNode node=new TreeNode(pre[preleft]);
            int mid=0;
            for (int i=inleft;i<=inright;i++){
                  if (pre[preleft]==in[i]){
                        mid=i;
                  }
            }
            node.left=creat(pre,in,preleft+1,preleft+(mid-inleft),inleft,mid-1);
            node.right=creat(pre,in,preleft+(mid-inleft)+1,preright,mid+1,inright);
            return node;
      }
}

/**

  • Two stacks are used to implement a queue, and the Push and Pop operations of the queue are completed. The element in the queue is of type int
  • First of all, we need to understand the queue. The queue is a first in, first out (queuing) structure, while the stack is a last in, first out structure.
  • Push and pop operations are required. Push is to join the end of the team similar to enqueue, while pop is to return and throw the front similar to dequeue. We assume that stack1 is used as a return and stack2 as a transit. Let's take a look at the picture below. Suppose 7, 3, 5 and 6 are in the queue, and 8 (push8) is to be added
    */
public class Stack {

    java.util.Stack<Integer> stack1=new java.util.Stack<>();
    java.util.Stack<Integer> stack2=new java.util.Stack<>();

    public void push(int node){
        while (!stack1.isEmpty()){
            stack2.push(stack1.pop());
        }
        stack2.push(node);
        while (!stack2.isEmpty()){
            stack1.push(stack2.pop());
        }
        stack2.clear();
    }
    public int pop(){
        return stack1.pop();
    }
}

/**

  • To move the first elements of an array to the end of the array, we call it the rotation of the array.
  • Input a rotation of a non decrementing array, and output the minimum elements of the rotation array.
  • For example, array {3,4,5,1,2} is a rotation of {1,2,3,4,5} and the minimum value of the array is 1.
  • NOTE: all the given elements are greater than 0. If the array size is 0, please return 0.
  • Train of thought:
  • It requires us to find the smallest number in such a series, non decreasing rotation, that is, such a series has two non decreasing consecutive strings. Finding the second non decrementing string header is the result.
  • However, we only need to find the minimum for the first time to finish. It doesn't time out because of the size of the array. Unable to provide more input data. The complexity is O(n);

*/

public class Xuanzhuanshuzu {
        public int minNumberInRotateArray(int[] array){
            if (array.length==0)return 0;
            int min=array[0];
            for (int i=0;i<array.length;i++){
                if (array[i]<min){
                    min=array[i];
                    break;
                }
            }
            return min;
        }

        int minNumberInRotateArray(vector<int> rotateArray){
            if (rotateArray.empty()){
                return 0;

                int low=0;
                int high=rotateArray.size()-1;
                int mid=0;

                while (low<high){
                    if (rotateArray[low] < rotateArray[high])
                        return rotateArray[low];
                    mid=low+(high-low)/2;
                    if (rotateArray[mid] > rotateArray[low])
                        low=mid+1;
                    else if (rotateArray[mid] < rotateArray[high])
                        high=mid;
                    else low++;
                }
                return rotateArray[low];
            }
        }
}

/**

  • Everyone knows the Fibonacci sequence. Now you need to input an integer n. please output the nth term of the Fibonacci sequence (starting from 0, 0).
  • n<=39
    */
public class Feibona {

    public int Fibonacci(int n){
        if (n==1||n==0){
            return n;
        }else{
            return Fibonacci(n-1+Fibonacci(n-2));
        }
    }
    public int Fibonacci2(int n){
        int Fibo[]=new int[40];
        Fibo[0]=0;
        Fibo[1]=1;
        for (int i=2;i<=n;i++){
            Fibo[i]=Fibo[i-1]+Fibo[i-2];
        }
        return Fibo[n];
    }
}
107 original articles published, 49 praised, 110000 visitors+
Private letter follow

Posted by squalls_dreams on Thu, 05 Mar 2020 02:56:08 -0800