搜索微信公衆號:'AI-ming3526'或者'計算機視覺這件小事' 獲取更多算法、機器學習乾貨python
csdn:https://blog.csdn.net/baidu_31657889/git
csdn:https://blog.csdn.net/abcgkj/github
github:https://github.com/aimi-cn/AILearners面試
這是由LeetCode官方推出的的經典面試題目清單~
這個模塊對應的是探索的初級算法~旨在幫助入門算法。咱們第一遍刷的是leetcode推薦的題目。
查看完整的劍指Offer算法題解析請點擊github連接:
github地址算法
打亂一個沒有重複元素的數組。編程
示例:數組
// 以數字集合 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();複製代碼
遍歷數組每一個位置,每次都隨機生成一個座標位置,而後交換當前位置和隨機位置的數字,這樣若是數組有n個數字,那麼也隨機交換了n組位置,從而達到了洗牌的目的。微信
pythondom
class Solution(object):
def __init__(self, nums):
"""
:type nums: List[int]
"""
self.data = nums
def reset(self):
"""
Resets the array to its original configuration and return it.
:rtype: List[int]
"""
return self.data
def shuffle(self):
"""
Returns a random shuffling of the array.
:rtype: List[int]
"""
# 方法一:
# ans = copy.deepcopy(self.data)
# random.shuffle(ans)
# return ans
#方法二
ans = copy.deepcopy(self.data)
for i in range(len(ans)):
j = random.randint(i, len(ans)-1)
ans[i], ans[j] = ans[j], ans[i]
return ans
# Your Solution object will be instantiated and called as such:
# obj = Solution(nums)
# param_1 = obj.reset()
# param_2 = obj.shuffle()複製代碼
AIMI-CN AI學習交流羣【1015286623】 獲取更多AI資料機器學習
分享技術,樂享生活:咱們的公衆號計算機視覺這件小事每週推送「AI」系列資訊類文章,歡迎您的關注!
本文由博客一文多發平臺 OpenWrite 發佈!