Leetcode刷题记录 剑指offer

面试题3:数组中重复数字

# 使用set,时间复杂度O(n),空间复杂度O(n)
class
Solution(object): def findRepeatNumber(self, nums): """ :type nums: List[int] :rtype: int """ a = set([]) for num in nums: if num in a: return num a.add(num)
# 桶思想,时间复杂度O(n),空间复杂度O(1)
class Solution(object):
    def findRepeatNumber(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        for i in range(len(nums)):
            val = nums[i]
            if val != i and val == nums[val]:
                return val
            nums[i], nums[val] = nums[val], nums[i]

面试题4:二维数组中的查找

# 从右上往左下推
class Solution(object):
    def findNumberIn2DArray(self, matrix, target):
        """
        :type matrix: List[List[int]]
        :type target: int
        :rtype: bool
        """
        if matrix == [] or matrix == [[]]:
            return False
        c = len(matrix[0])-1
        l = 0
        while True:
            if matrix[l][c] == target:
                return True
            if matrix[l][c] > target:
                c -= 1
            else:
                l += 1
            if l > len(matrix)-1 or c < 0:
                return False

面试题5:替换空格

面试题6:从尾到头打印链表

面试题7:重建二叉树

class Solution(object):
    def buildTree(self, preorder, inorder):
        """
        :type preorder: List[int]
        :type inorder: List[int]
        :rtype: TreeNode
        """
        def helper(inc_start, inc_end):
            if inc_start == inc_end:
                return None
            inc_value = preorder[self.pre_index]
            root = TreeNode(inc_value)
            self.pre_index += 1
            root.left = helper(inc_start, inc_value_map[inc_value])
            root.right = helper(inc_value_map[inc_value] + 1, inc_end)
            return root
        self.pre_index = 0
        inc_value_map = {v: k for k, v in enumerate(inorder)}
        return helper(0, len(inorder))

面试题9:用两个栈实现队列

面试题10-I:斐波那契数列

面试题10-II:青蛙跳台阶问题

猜你喜欢

转载自www.cnblogs.com/weswes/p/12306094.html