LeetCode初級算法--設(shè)計問題01:Shuffle an Array (打亂數(shù)組)
一、引子
這是由LeetCode官方推出的的經(jīng)典面試題目清單~
這個模塊對應(yīng)的是探索的初級算法~旨在幫助入門算法。我們第一遍刷的是leetcode推薦的題目。
二、題目
打亂一個沒有重復(fù)元素的數(shù)組。
示例:
// 以數(shù)字集合 1, 2 和 3 初始化數(shù)組。
int[] nums = {1,2,3};
Solution solution = new Solution(nums);
// 打亂數(shù)組 [1,2,3] 并返回結(jié)果。任何 [1,2,3]的排列返回的概率應(yīng)該相同。
solution.shuffle();
// 重設(shè)數(shù)組到它的初始狀態(tài)[1,2,3]。
solution.reset();
// 隨機返回數(shù)組[1,2,3]打亂后的結(jié)果。
solution.shuffle();
1、思路
遍歷數(shù)組每個位置,每次都隨機生成一個坐標(biāo)位置,然后交換當(dāng)前位置和隨機位置的數(shù)字,這樣如果數(shù)組有n個數(shù)字,那么也隨機交換了n組位置,從而達到了洗牌的目的。
2、編程實現(xiàn)
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()
本文由博客一文多發(fā)平臺 OpenWrite 發(fā)布!
審核編輯 黃昊宇
-
人工智能
+關(guān)注
關(guān)注
1804文章
48423瀏覽量
244725 -
機器學(xué)習(xí)
+關(guān)注
關(guān)注
66文章
8478瀏覽量
133819 -
深度學(xué)習(xí)
+關(guān)注
關(guān)注
73文章
5546瀏覽量
122283 -
leetcode
+關(guān)注
關(guān)注
0文章
20瀏覽量
2405
發(fā)布評論請先 登錄
相關(guān)推薦
pads9.5在creat array時,會打亂我排列好的元器件,是怎么回事?
請教大神關(guān)于IMAQ模塊中的問題:IMAQCreate與 IMAQ Image To Array函數(shù)的算法原理是什么?
詳解Spark Shuffle原理及Shuffle操作問題解決
數(shù)組元素超過9個如何根據(jù) Array 自動創(chuàng)建 Cluster
LeetCode 215. Kth Largest Element in an Array
LabVIEW初級教程之數(shù)組和簇的相關(guān)例程免費下載

LeetCode初級算法-其他01:位1的個數(shù)
LeetCode初級算法-設(shè)計問題02:最小棧
LeetCode初級算法-動態(tài)規(guī)劃01:爬樓梯
ARRAY 數(shù)據(jù)類型的變量
?數(shù)組和C++ std::array詳解

評論