这次是实操,上LeetCode找3道题来写
第一道题:打乱数组
思路:
1.将原始数组深复制进类中的
self.origin
(避免干扰)
2.reset时返回原始数组
3.shuffle时先把self.origin深复制给一个临时变量tmp并对其调用random.shuffle(tmp)并返回
代码:
import random import copy class Solution: def __init__(self, nums): """ :type nums: List[int] """ self.origin = copy.copy(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] """ tmp = copy.copy(self.origin) random.shuffle(tmp) return tmp # Your Solution object will be instantiated and called as such:
第二道题: 回文数
思路:
1.将int转换为str
2.将str反转
3.比较是否相同
代码:
class Solution: def isPalindrome(self, x): """ :type x: int :rtype: bool """" a = str(x) b = a[::-1] if a == b: return True return False
第三道题: 全排列
思路:
调用itertools库中的permutation函数完成(本来需要自己写递归,可能这就是高级语言吧)
代码:
import itertools class Solution: def permute(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ x=list(itertools.permutations(nums,len(nums))) return x