• 剑指offer(1-10)


    题目一

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

    C++代码如下(暴力解法):

    class Solution {
    public:
        bool Find(int target, vector<vector<int> > array) {
            bool isFound = false;
            for(int i = 0; i < array.size(); i++){
                for(int j = 0; j < array[i].size(); j++){
                    if(false == isFound && target == array[i][j]){
                        isFound = true;
                    }
                }
            }
            return isFound;
        }
    };
    

    JAVA代码如下(暴力解法):

    public class Solution {
        public boolean Find(int target, int [][] array) {
            boolean Flag = false;
            for(int i = 0; i < array.length; i++){
                for(int j = 0; j < array[i].length; j++) {
                    if(Flag == false && array[i][j] == target)
                        Flag = true;
                }
            }
            return Flag;
        }
    

    C++最优解如下:

    class Solution {
    public:
        bool Find(int target, vector<vector<int> > array) {
            bool isFound = false;
            int row = 0;
        	int col = array[0].size() - 1;
        	while (row < array.size() && col >= 0) {
                if(target > array[row][col]) {
                    row++;
                }else if(target < array[row][col]) {
                    col--;
                }else {
                    isFound = true;
                    break;
                }
    		}
            return isFound;
        }
    };
    

    JAVA最优解如下:

    public class Solution {
        public boolean Find(int target, int [][] array) {
            boolean Flag = false;
        	int row = 0;
        	int col = array[0].length - 1;
        	while (row < array.length && col >= 0) {
                if(target > array[row][col]) {
                    row++;
                }else if(target < array[row][col]) {
                    col--;
                }else {
                    Flag = true;
                    break;
                }
    		}
        	return Flag;
        }
    }
    

    题目二

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

    class Solution {
    public:
    	void replaceSpace(char *str,int length) {
            if (str == NULL || length <= 0)
    			return;
    	int i = length - 1, j;
    	int len = length;
    	//从后往前进行遍历 
    
    	for (int i = length - 1; i >= 0; i--) {
    		if (str[i] == ' ') {
    		len += 2;
    		for (j = len - 1; j > i+2; j--) {
    			str[j] = str[j - 2];
    		}
    		str[i] = '%';
    		str[i + 1] = '2';
    		str[i + 2] = '0';
    		}
    	}
    	str[len] = ''; 
    	}
    };
    

    C++最优解如下:

    class Solution {
    public:
    	void replaceSpace(char *str,int length) {
            if (str == nullptr && length < 0)
    			return;
    	//获得原始字符串长度和空格数   
    
    	int OrignalLength = 0;
    	int NumberOfBlank = 0;
    	int i = 0;
    	while (str[i] != '') {
    		OrignalLength++;
    		if (str[i] == ' ')
    			NumberOfBlank++;
    		++i;
    	}
    	//将字符串空格替换为%20   
    
    	int NewLength = OrignalLength + 2 * NumberOfBlank;
    	if (NewLength > length)
    		return;
    	int indexOfOriginal = OrignalLength;
    	int indexOfNew = NewLength;
    	while (indexOfOriginal >= 0 && indexOfNew > indexOfOriginal) {
    		if (str[indexOfOriginal] == ' ') {
    			str[indexOfNew--] = '0';
    			str[indexOfNew--] = '2';
    			str[indexOfNew--] = '%';
    			indexOfOriginal--;
    		}else { 
    			str[indexOfNew--] = str[indexOfOriginal--];
    		}	
    	}
        }
    };
    

    JAVA最优解如下:

    public class Solution {
        public String replaceSpace(StringBuffer str) {
        	if(str == null)
    		return null;
    	StringBuilder sb = new StringBuilder();
    	for(int i = 0; i < str.length(); i++) {
    		if(String.valueOf(str.charAt(i)).equals(" ")) {
    			sb.append("%20");
    		}else {
    			sb.append(str.charAt(i));
    		}
    	}
    	return String.valueOf(sb);
        }
    }
    

    题目三

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

    C++最优解如下:

    //利用栈和容器逆向打印链表   
    
    vector<int> printListFromTailToHead04(ListNode* head) {
        vector <int> nodeVector;
        stack<int> stack;
        ListNode *p = head;
        if (head != nullptr) {
            while (p != nullptr) {
                stack.push(p->val);
                p = p->next;
            }
            while (!stack.empty()) {
                nodeVector.push_back(stack.top());
                stack.pop();
            }
        }
        return nodeVector;
    
    }
    

    JAVA最优解如下:

    import java.util.ArrayList;
    import java.util.Stack;
    public class Solution {
        public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
            Stack<Integer> stack = new Stack<Integer>(); 
    	    while(listNode != null) {
    	    	stack.push(listNode.val);
    	    	listNode = listNode.next;
    	    }
    	    
    	    ArrayList<Integer> list = new ArrayList<Integer>();
    	    while(!stack.empty()) {
    	    	list.add(stack.pop());
    	    }
    		return list;
        }
    }
    

    题目四

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

    C++最优解如下:

    TreeNode* reConstructBinaryTree(vector<int> pre, vector<int> vin) {
            int inLength = vin.size();
    	if (inLength == 0)
    		return NULL;
    
    	vector<int> left_pre, right_pre, left_in, right_in;
    
    	//创建根节点,根节点是前序遍历的第一个数  
    
    	TreeNode* head = new TreeNode(pre[0]);
    
    	//找到中序遍历根节点所在位置,存放在变量rootIndex中  
    
    	int rootIndex = 0;
    	for (int i = 0; i < inLength; i++) {
    		if (vin[i] == pre[0]) {
    			rootIndex = i;
    			break;
    		}
    	}
    
    	//对于中序遍历,根节点左边的节点位于二叉树的左边,根节点右节点位于二叉树的右边  
    
        //利用上述这点,对二叉树进行归并   
    
    	for (int i = 0; i < rootIndex; i++) {
    		left_in.push_back(vin[i]);
    		left_pre.push_back(pre[i+1]);//前序第一个为根节点
    	}
    	for (int i = rootIndex + 1; i < inLength; i++) {
    		right_in.push_back(vin[i]);
    		right_pre.push_back(pre[i]);
    	}
    
    	//取出前序和中序遍历根节点左子树和右字树,进行递归再区分左右字树直到叶节点   
    
    	head->left = reConstructBinaryTree(left_pre, left_in);
    	head->right = reConstructBinaryTree(right_pre, right_in);
    	return head;
    }
    

    JAVA最优解如下:

    	//已知前序和中序遍历,重建二叉树返回头结点    
        
    	public static TreeNode reConstructBinaryTree(int [] pre,int [] in) {
    		TreeNode root = reConstructBinaryTree(pre, 0, pre.length-1, in, 0, in.length-1);
    		return root;
            }
    	
    	private static TreeNode reConstructBinaryTree(int[] pre,int startPre,int endPre,int[] in,int startIn,int endIn) {
    		if(startPre > endPre || startIn > endIn)
    			return null;
    		TreeNode root = new TreeNode(pre[startPre]);
    		
    		for(int i = startIn; i <= endIn; i++) {
    			if(in[i] == pre[startPre]) {
    				root.left = reConstructBinaryTree(pre, startPre+1, startPre+i-startIn, in, startIn, i-1);
    				root.right = reConstructBinaryTree(pre, i-startIn+startPre+1, endPre, in, i+1, endIn);
    				break;
    			}
    		}
    		return root;
    	}
    

    题目五

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

    C++最优解如下:

    class Solution
    {
    public:
    	void push(int node) {
    		stack1.push(node);
    	}
    	int pop() {
    	    if (stack2.empty()) {
    		while (!stack1.empty()) {
    		    int value = stack1.top();
    		    stack2.push(value);
    	            stack1.pop();
    		}
    	    }
    	    int value = stack2.top();
    	    stack2.pop();
    	    return value;
    	}
    private:
    	stack<int> stack1;
    	stack<int> stack2;
    };
    

    JAVA最优解如下:

    import java.util.Stack;
    
    public class Solution {
        Stack<Integer> stack1 = new Stack<Integer>();
        Stack<Integer> stack2 = new Stack<Integer>();
        
        public void push(int node) {
            stack1.push(node);
        }
        
        public int pop() {
            if(stack2.empty()) {
                while(!stack1.empty()) {
                    stack2.push(stack1.pop());
                }
            }
            return stack2.pop();
        }
    }
    

    题目六

    把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。 输入一个非递减排序的数组的一个旋转,输出旋转数组的最小元素。 例如数组{3,4,5,1,2}为{1,2,3,4,5}的一个旋转,该数组的最小值为1。 NOTE:给出的所有元素都大于0,若数组大小为0,请返回0。

    C++暴力解如下:

    class Solution {
    public:
        int minNumberInRotateArray(vector<int> rotateArray) {
            int length = rotateArray.size();
    	if (length == 0)
    		return 0;
    	for (int i = 0; i <= length-1; i++) {
    		if (rotateArray[i + 1] < rotateArray[i]) {
    			return rotateArray[i + 1];
    		}
    	}
    	return rotateArray[0];
        }
    };
    

    JAVA暴力解如下:

    import java.util.ArrayList;
    public class Solution {
       public int minNumberInRotateArray(int[] array) {
            if (array.length == 0)
                return 0;
            for (int i = 0; i < array.length - 1; i++) {
                if (array[i] > array[i + 1])
                    return array[i + 1];
            }
            return array[0];
        } 
    }
    

    C++最优解如下:

    class Solution {
    public:
        int minNumberInRotateArray(vector<int> rotateArray) {
            int low = 0 ; int high = rotateArray.size() - 1;   
            while(low < high){
                int mid = low + (high - low) / 2;        
                if(rotateArray[mid] > rotateArray[high]){
                    low = mid + 1;
                }else if(rotateArray[mid] == rotateArray[high]){
                    high = high - 1;
                }else{
                    high = mid;
                }   
            }
            return rotateArray[low];
        }
    };
    

    JAVA最优解如下:

    import java.util.ArrayList;
    public class Solution {
       public int minNumberInRotateArray(int[] array) {
           if (array.length == 0)
               return 0;
           int left = 0;
           int right = array.length - 1;
           int middle = -1;
           while (array[left]>=array[right]) {
               if(right-left==1){
                   middle = right;
                   break;
               }
               middle = left + (right - left) / 2;
               if (array[middle] >= array[left]) {
                   left = middle;
               }
               if (array[middle] <= array[right]) {
                   right = middle;
               }
           }
           return array[middle];
        } 
    }
    

    题目七

    大家都知道斐波那契数列,现在要求输入一个整数n,请你输出斐波那契数列的第n项。n<=39

    C++最优解如下:

    class Solution {
    public:
        int Fibonacci(int n) {
    	int result[2] = {0,1};
    	if (n < 2) {
    		return result[n];
    	}
    	long long fibNMinusOne = 1;
    	long long fibNMinusTwo = 0;
    	long long fibN = 0;
    	for (int i = 2; i <= n; i++) {
    		fibN = fibNMinusOne + fibNMinusTwo;
    		fibNMinusTwo = fibNMinusOne;
    		fibNMinusOne = fibN;
    	}
    	return fibN;
        }
    };
    

    JAVA最优解如下:

    public class Solution {
        public int Fibonacci(int n) {
            int[] result = {0,1};
    	if(n < 2) {
    		return result[n];
    	}
    	int FiboNMinusOne = 1;
    	int FiboNMinusTwo = 0;
    	int FiboN = 0;
    	for(int i=2; i <= n; i++) {
    		FiboN = FiboNMinusOne + FiboNMinusTwo;
    
    		FiboNMinusTwo = FiboNMinusOne;
    		FiboNMinusOne = FiboN;
    	}
    	return FiboN;
        }
    }
    

    题目八

    一只青蛙一次可以跳上1级台阶,也可以跳上2级。求该青蛙跳上一个n级的台阶总共有多少种跳法。

    C++最优解如下:

    class Solution {
    public:
        int jumpFloor(int number) {
            int result[2] = {1,2};
    	if(number <= 2)
    		return result[number-1];
    	int FiboNMinusOne = 2;
    	int FiboNMinusTwo = 1;
    	int FiboN = 0;
    	for(int i=3; i <= number; i++) {
    		FiboN = FiboNMinusOne + FiboNMinusTwo;
    		FiboNMinusTwo = FiboNMinusOne;
    		FiboNMinusOne = FiboN;
    	}
    	return FiboN;
        }
    };
    

    JAVA最优解如下:

    public class Solution {
        public int JumpFloor(int target) {
            int[] result = {1,2};
    	if(target <= 2)
    		return result[target-1];
    	int FiboNMinusOne = 2;
    	int FiboNMinusTwo = 1;
    	int FiboN = 0;
    	for(int i=3; i <= target; i++) {
    		FiboN = FiboNMinusOne + FiboNMinusTwo;
    		FiboNMinusTwo = FiboNMinusOne;
    		FiboNMinusOne = FiboN;
    	}
    	return FiboN;
        }
    }
    

    题目九

    一只青蛙一次可以跳上1级台阶,也可以跳上2级……它也可以跳上n级。求该青蛙跳上一个n级的台阶总共有多少种跳法。

    C++最优解如下:

    class Solution {
    public:
        int jumpFloorII(int number) {
            int result[2] = {0,1};
            if(number == 1 || number == 0)
                return result[number];
            int initialNum = 1;
            int jumpNum = 0;
            for(int i=2; i <= number; i++){
                jumpNum = 2 * initialNum;
                initialNum = jumpNum;
            }
            return jumpNum;
        }
    };
    

    JAVA最优解如下:

    public class Solution {
        public int JumpFloorII(int target) {
            int[] result = {0,1};
            if(target == 1 || target == 0)
                return result[target];
            int initialNum = 1;
            int jumpNum = 0;
            for(int i=2; i <= target; i++){
                jumpNum = 2 * initialNum;
                initialNum = jumpNum;
            }
            return jumpNum;
        }
    }
    

    题目十

    我们可以用2*1的小矩形横着或者竖着去覆盖更大的矩形。请问用n个2*1的小矩形无重叠地覆盖一个2*n的大矩形,总共有多少种方法?

    C++最优解如下:

    class Solution {
    public:
        int rectCover(int number) {
            int result[2] = {1,2};
            if(number == 1 || number == 2)
                return result[number-1];
            int fiboNMinusOne = 2;
            int fiboNMinusTwo = 1;
            int fibN = 0;
            for(int i=3; i<=number; i++){
                fibN = fiboNMinusOne + fiboNMinusTwo;
                fiboNMinusTwo = fiboNMinusOne;
                fiboNMinusOne = fibN;
            }
            return fibN;
        }
    };
    

    JAVA最优解如下:

    public class Solution {
        public int RectCover(int target) {
            int[] result = {1,2};
            if(target == 1 || target == 2)
                return result[target-1];
            int fiboNMinusOne = 2;
            int fiboNMinusTwo = 1;
            int fibN = 0;
            for(int i=3; i<=target; i++){
                fibN = fiboNMinusOne + fiboNMinusTwo;
                fiboNMinusTwo = fiboNMinusOne;
                fiboNMinusOne = fibN;
            }
            return fibN;
        }
    }
    
  • 相关阅读:
    HTML5 <meta> 标签属性,所有meta用法
    C#中导出数据到Excel表格中 逗号
    .net MVC 中缓存的使用 逗号
    MVC 过滤器 逗号
    .Net 分布式技术比较 逗号
    将DataTable导出为Excel (XML Spreadsheet).
    AntiTD
    三星WP7手机MANGO一分钟完美越狱
    SPGridView 研究笔记 Part 3 分组
    Silverlight 4 Binding Cheatsheet [转]
  • 原文地址:https://www.cnblogs.com/zhongzhaoxie/p/13064314.html
Copyright © 2020-2023  润新知