剑指offer1

来源:互联网 发布:淘宝开店冲话费 编辑:程序博客网 时间:2024/04/27 21:08

题目:二维数组中的查找

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

c++:

class Solution {public:    bool Find(int target, vector<vector<int> > array) {        int rowcount = array.size();//行        int colcount = array[0].size();//列        int i ,j;        for( i=rowcount-1,j=0;i>=0&&j<colcount;)//注意符号        {            if(target==array[i][j])            return true;            if(target>array[i][j])            {                j++;                continue;            }            if(target<array[i][j])            {                i--;                continue;            }        }        return false;//符号    }};

python:

class Solution:    def Find(self, target,array):        if array == []:            return False        rawnum = len(array)        colnum = len(array[0])        i = colnum - 1        j = 0        while i >= 0 and j < rawnum:            if array[j][i] < target:                j += 1            elif array[j][i] > target:                i -= 1            else:                return True        return False

题目:替换空格

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

c++:

class Solution {public:    void replaceSpace(char *str,int length) {        if (str==NULL||length<0)            return;        int oldlen =0;        int oldnum =0;        int i = 0;        while(str[i]!='\0')//c++中没有双引号        {            oldlen++;            if (str[i]==' ')//两个等号            {                oldnum++;            }            i++;        }        int newlen = oldlen + oldnum*2;        if(newlen>length)            return;        int poldlen = oldlen;        int pnewlen = newlen;        while(poldlen>=0&&pnewlen>poldlen)//>=0        {            if(str[poldlen]==' ')            {                str[pnewlen--]='0';                str[pnewlen--]='2';                str[pnewlen--]='%';            }            else            {                str[pnewlen--]=str[poldlen];            }            poldlen--;        }    }};

python:

# -*- coding:utf-8 -*-class Solution:    # s 源字符串    def replaceSpace(self, s):        # write code here        tempstr = ''        for c in s:#看了半天没发现这里不能用括号            if c==' ':                tempstr = tempstr+'%20'            else:                tempstr = tempstr+c        return tempstr

使用replace:

return s.replace(' ', '%20')

题目:从尾到头打印链表

c++:

class Solution {public:    vector<int> printListFromTailToHead(ListNode* head) {        vector<int> value;        if(head!=NULL)        {            value.insert(value.begin(),head->val);            while(head->next!=NULL)            {                value.insert(value.begin(),head->next->val);                head = head->next;            }        }        return value;    }};

python:

class Solution:    def printListFromTailToHead(self, listNode):        l = []        head = listNode        while head:            l.insert(0, head.val)            head = head.next        return l

题目:重建二叉树

c++

class Solution {    public:        struct TreeNode* reConstructBinaryTree(vector<int> pre,vector<int> in) {            int inlen=in.size();            if(inlen==0)                return NULL;            vector<int> left_pre,right_pre,left_in,right_in;            //创建根节点,根节点肯定是前序遍历的第一个数            TreeNode* head=new TreeNode(pre[0]);            //找到中序遍历根节点所在位置,存放于变量gen中            int gen=0;            for(int i=0;i<inlen;i++)            {                if (in[i]==pre[0])                {                    gen=i;                    break;                }            }            //对于中序遍历,根节点左边的节点位于二叉树的左边,根节点右边的节点位于二叉树的右边            //利用上述这点,对二叉树节点进行归并            for(int i=0;i<gen;i++)            {                left_in.push_back(in[i]);                left_pre.push_back(pre[i+1]);//前序第一个为根节点            }            for(int i=gen+1;i<inlen;i++)            {                right_in.push_back(in[i]);                right_pre.push_back(pre[i]);            }            //和shell排序的思想类似,取出前序和中序遍历根节点左边和右边的子树            //递归,再对其进行上述所有步骤,即再区分子树的左、右子子数,直到叶节点           head->left=reConstructBinaryTree(left_pre,left_in);           head->right=reConstructBinaryTree(right_pre,right_in);           return head;        }    };

python:

class Solution:    def reConstructBinaryTree(self, pre, tin):        if not pre and not tin:            return None        root = TreeNode(pre[0])        if set(pre) != set(tin):            return None        i = tin.index(pre[0])        root.left = self.reConstructBinaryTree(pre[1:i+1], tin[:i])        root.right = self.reConstructBinaryTree(pre[i+1:], tin[i+1:])        return root

c++

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

python

class Solution:    def __init__(self):        self.stack1=[]        self.stack2=[]    def push(self, node):        self.stack1.append(node)    def pop(self):        if len(self.stack1)==0 and len(self.stack2)==0:            return        elif len(self.stack2)==0:            while len(self.stack1)>0:                self.stack2.append(self.stack1.pop())        return self.stack2.pop()
原创粉丝点击