LeetCode初級演算法--設計問題01:Shuffle an Array (打亂陣列)
搜索微信公眾號:'AI-ming3526'或者'計算機視覺這件小事' 獲取更多演算法、機器學習干貨
csdn:https://blog.csdn.net/baidu_31657889/
csdn:https://blog.csdn.net/abcgkj/
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();
1、思路
遍歷陣列每個位置,每次都隨機生成一個坐標位置,然后交換當前位置和隨機位置的數字,這樣如果陣列有n個數字,那么也隨機交換了n組位置,從而達到了洗牌的目的,
2、編程實作
python
class Solution(object):
def __init__(self, nums):
"""
:type nums: List[int]
"""
self.data = https://www.cnblogs.com/aimi-cn/p/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 發布!
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/65622.html
標籤:其他
