Leetcode——初级部分——设计问题部分——Python实现

Shuffle an Array

打乱一个没有重复元素的数组。

示例:

// 以数字集合 1, 2 和 3 初始化数组。
int[] nums = {1,2,3};
Solution solution = new Solution(nums);

// 打乱数组 [1,2,3] 并返回结果。任何 [1,2,3]的排列返回的概率应该相同。
solution.shuffle();

// 重设数组到它的初始状态[1,2,3]。
solution.reset();

// 随机返回数组[1,2,3]打乱后的结果。
solution.shuffle();

我的解答:

class Solution:

    def __init__(self, nums):
        """
        :type nums: List[int]
        """
        self.origin = nums
        

    def reset(self):
        """
        Resets the array to its original configuration and return it.
        :rtype: List[int]
        """
        return self.origin

    def shuffle(self):
        """
        Returns a random shuffling of the array.
        :rtype: List[int]
        """
        import random
        newNums = self.origin[:]
        random.shuffle(newNums)
        return newNums


# Your Solution object will be instantiated and called as such:
# obj = Solution(nums)
# param_1 = obj.reset()
# param_2 = obj.shuffle()

最小栈

设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。

  • push(x) -- 将元素 x 推入栈中。
  • pop() -- 删除栈顶的元素。
  • top() -- 获取栈顶元素。
  • getMin() -- 检索栈中的最小元素。

示例:

MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin();   --> 返回 -3.
minStack.pop();
minStack.top();      --> 返回 0.
minStack.getMin();   --> 返回 -2.

我的解答:

我用Python内建的列表来实现。

class MinStack:

    def __init__(self):
        """
        initialize your data structure here.
        """
        self.nums = list()

    def push(self, x):
        """
        :type x: int
        :rtype: void
        """
        self.nums.append(x)

    def pop(self):
        """
        :rtype: void
        """
        self.nums.pop()

    def top(self):
        """
        :rtype: int
        """
        return self.nums[-1]

    def getMin(self):
        """
        :rtype: int
        """
        return min(self.nums)


# Your MinStack object will be instantiated and called as such:
# obj = MinStack()
# obj.push(x)
# obj.pop()
# param_3 = obj.top()
# param_4 = obj.getMin()



猜你喜欢

转载自blog.csdn.net/dta0502/article/details/80959222