剑指offer·1-11

1、二维数组是否存在某个值(二维数组从左到右从上到下递增)

# 二维数组是否存在某个值(二维数组从左到右从上到下递增)
# 方法:从左下角开始找,目标大于当前数,向右移,小于向左移

import numpy as np


class Solution:
    def Find(self, target, array):
        r, c = array.shape
        x = r-1
        y = 0
        while y < c and x >= 0:
            item = array[x][y]
            if target > item:
                y += 1
            elif target < item:
                x -= 1
            elif target == item:
                return True
        return False


if __name__ == '__main__':
    array = np.array([[1, 2, 8, 9], [2, 4, 9, 12], [4, 7, 10, 13], [6, 8, 11, 15]])
    target = 11
    a = Solution()
    print(a.Find(target, array))

2、替换字符串中的空格

# -*- coding:utf-8 -*-
# 替换字符串中的空格


class Solution:
    # s 源字符串
    def replaceSpace(self, s):
        # write code here
        s = list(s)
        L = len(s)
        for i in range(L):
            if s[i] == ' ':
                s[i] = '%20'
        return ''.join(s)


if __name__ == '__main__':
    S = Solution()
    s = 'hallo world'
    print(S.replaceSpace(s))

3、返回从尾部到头部的列表值序列

# -*- coding:utf-8 -*-
class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None
        
class Solution:
    # 返回从尾部到头部的列表值序列,例如[1,2,3]
    def printListFromTailToHead(self, listNode):
        # write code here
        a = []
        while listNode:
            a.insert(0, listNode.val)
            listNode = listNode.next
        return a

4、前序中序遍历重建二叉树,返回构造的TreeNode根节点

class TreeNode:
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None

#  前序中序遍历重建二叉树
class Solution:
    # 返回构造的TreeNode根节点

    def reConstructBinaryTree(self, pre, tin):
        # write code here
        if len(pre) == 0:
            return None
        if len(pre) == 1:
            return TreeNode(pre[0])
        else:
            root = TreeNode(pre[0])
            root.left = self.reConstructBinaryTree(pre[1:tin.index(pre[0])+1], tin[0:tin.index(pre[0])])
            root.right = self.reConstructBinaryTree(pre[tin.index(pre[0])+1:], tin[tin.index(pre[0])+1:])
        return root

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

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


class Solution:
    def __init__(self):
        self.stack1 = []
        self.stack2 = []

    def push(self, node):
        # write code here
        self.stack1.append(node)

    def pop(self):
        if self.stack2 == []:
            while len(self.stack1) != 0:
                item = self.stack1.pop()
                self.stack2.append(item)
            result = self.stack2.pop()
            while len(self.stack2) != 0:
                self.stack1.append(self.stack2.pop())
            return result
        else:
            return self.stack2.pop()


if __name__ == '__main__':
    s = Solution()
    s.stack1 = ["P", "PSH2", "PSH3", "POP", "POP", "PSH4", "POP", "PSH5", "POP", "POP"]
    print(s.pop())
    s.push('O')
    print(s.stack1)

6、非递减旋转数组中的最小值

# 非递减旋转数组中的最小值


class Solution:
    def minNumberInRotateArray(self, rotateArray):
        # write code here
        if len(rotateArray) == 0:
            return 0
        else:
            low = 0
            high = len(rotateArray) - 1
            while low < high:
                mid = low + (high - low) // 2
                print(low, mid, high)
                if rotateArray[high] < rotateArray[mid]:
                    low = mid + 1
                elif rotateArray[high] == rotateArray[mid]:
                    high = high - 1
                else:
                    high = mid
            return rotateArray[low]


if __name__ == '__main__':
    s = Solution()
    rotateArray = [3, 3, 4, 5, 1, 2]
    print(s.minNumberInRotateArray(rotateArray))

7、斐波那契数列第n项 f_n = f_n-1 + f_n-2

# -*- coding:utf-8 -*-
# 斐波那契数列第n项 f_n = f_n-1 + f_n-2
class Solution:
    def Fibonacci(self, n):
        # write code here
        f = [None]*40
        f[0] = 0
        f[1] = 1
        for i in range(n+1):
            if i > 1:
                f[i] = f[i-1] + f[i-2]
        return f[n]


if __name__ == '__main__':
    s = Solution()
    print(s.Fibonacci(30))


8、一只青蛙一次可以跳上1级台阶,也可以跳上2级。求该青蛙跳上一个n级的台阶总共有多少种跳法(先后次序不同算不同的结果)

# 一只青蛙一次可以跳上1级台阶,也可以跳上2级。求该青蛙跳上一个n级的台阶总共有多少种跳法(先后次序不同算不同的结果)
# 跳n级台阶相当于n-1级跳一次 或n-2级条一次 f_n = f_n-1 + f_n-2


class Solution:
    # def jumpFloor(self, number):
    #     # write code here
    #     if number <= 0:
    #         return 0
    #     elif number == 1:
    #         return 1
    #     elif number == 2:
    #         return 2
    #     else:
    #         f_l = 1
    #         f_h = 2
    #         for i in range(2, number):
    #             # print(i)
    #             f_n = f_h + f_l
    #             f_l = f_h
    #             f_h = f_n
    #         return f_n

    def jumpFloor(self, number):
        # write code here
        a = 0
        b = 1
        for i in range(number):
            a, b = b, a+b
        return b


if __name__ == '__main__':
    s = Solution()
    print(s.jumpFloor(5))

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

# 一只青蛙一次可以跳上1级台阶,也可以跳上2级……它也可以跳上n级。求该青蛙跳上一个n级的台阶总共有多少种跳法。
# f(n) = f(1) + f(2) + ...+ f(n-1)
# f(n) = 2*f(n-1)


class Solution:
    def jumpFloorII(self, number):
        # write code here
        if number == 1:
            return 1
        else:
            return 2*self.jumpFloorII(number-1)


if __name__ == '__main__':
    s = Solution()
    print(s.jumpFloorII(4))

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

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


class Solution:
    def rectCover(self, number):
        if number <= 0:
            return 0
        elif number == 1:
            return 1
        elif number == 2:
            return 2
        else:
            a = 1
            b = 2
            for i in range(3, number):
                a, b = b, a + b
            return a+b


if __name__ == '__main__':
    s = Solution()
    print(s.rectCover(4))

11、输入一个整数,输出该数二进制表示中1的个数。其中负数用补码表示。

# 输入一个整数,输出该数二进制表示中1的个数。其中负数用补码表示。
# 1100 - 1 = 1011; 1100 & 1011 = 1000(做一次位与,减少一个1)

class Solution:
    def NumberOf1(self, n):
        count = 0
        if n < 0:
            n = n & 0xffffffff
        while n != 0:
            n = n & n-1
            count += 1
        return count


if __name__ == '__main__':
    s = Solution()
    print(s.NumberOf1(1024))

你可能感兴趣的:(code,python)