384. Shuffle an Array

2024-04-10 07:32
文章标签 array shuffle 384

本文主要是介绍384. Shuffle an Array,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

文章目录

  • 384. Shuffle an Array
    • Approach 1 : Mark Element
      • Complexity Analysis
    • Approach 2 : Fish_Yates
      • Proof:
      • Complexity Analysis
    • Summary
      • 1. Random Value
      • 2. Re-emphasize: [left-opened right-closed)
      • 3. Shuffle Method

384. Shuffle an Array

https://leetcode.com/problems/shuffle-an-array/

Shuffle a set of numbers without duplicates.

Approach 1 : Mark Element

class Solution {vector<int> nums;
public:Solution(vector<int>& nums) {this->nums = nums;}/** Resets the array to its original configuration and return it. */vector<int> reset() {return nums;}/** Returns a random shuffling of the array. */vector<int> shuffle() {vector<int> ans(nums.size());vector<bool> mark(nums.size(), 0);int findIndex;for(int i=ans.size()-1; i>=0; i--) {int random = rand()%(i + 1) + 1;int n = 0;for(int j = 0; j<mark.size(); j++) {if(mark[j] == 0) {n++;if(n == random) {mark[j] = 1;ans[i] = nums[j];break;}}}            }return ans;}
};/*** Your Solution object will be instantiated and called as such:* Solution* obj = new Solution(nums);* vector<int> param_1 = obj->reset();* vector<int> param_2 = obj->shuffle();*/

Runtime: 208 ms, faster than 58.55% of C++ online submissions for Shuffle an Array.

Memory Usage: 31.3 MB, less than 21.43% of C++ online submissions for Shuffle an Array.

Complexity Analysis

  • Time complexity : O ( n 2 ) O(n^2) O(n2)

    Since we go through the array nums of length n. And for each character, we go through the array mark of length n. So the quadratic time complexity arises.

  • Space complexity : O ( n ) O(n) O(n)

    Because we need to use linear additional space to store the original array for reset operation.

    Also we need to mark the elements that are used. so we another linear additional space to store the mark flag for each element.

    So the total space is n + n = 2 n = O ( n ) n + n = 2n = O(n) n+n=2n=O(n)

Approach 2 : Fish_Yates

Walk through all positions.

For each current position, select an random position and swap the value of the two position.

Proof:

  • For the first position, the probability is 1 n \frac{1}{n} n1 obviously for each value [ 0 , n ) [0, n) [0,n).*

    So the probability of left values [ 1 , n ) [1, n) [1,n) is n − 1 n \frac{n-1}{n} nn1 .

  • For the second position, select an random value from [ 1 , n ) [1, n) [1,n). the probability is 1 n − 1 \frac{1}{n - 1} n11 obviously for each value [ 1 , n ) [1, n) [1,n) .

    Because of n − 1 n ∗ 1 n − 1 = 1 n \frac{n-1}{n}*\frac{1}{n-1} = \frac{1}{n} nn1n11=n1

    For the second position, the probability is 1 n \frac{1}{n} n1 for each value of [ 0 , n ) [0, n) [0,n)

    So the probability of left values [ 2 , n ) [2, n) [2,n) is n − 2 n \frac{n-2}{n} nn2 .

  • For the third position, select an random value from [ 2 , n ) [2, n) [2,n). the probability is 1 n − 2 \frac{1}{n - 2} n21 obviously for each value [ 2 , n ) [2, n) [2,n) .

    because of n − 2 n ∗ 1 n − 2 = 1 n \frac{n-2}{n}*\frac{1}{n-2} = \frac{1}{n} nn2n21=n1

    For the third position, the probability is 1 n \frac{1}{n} n1 for each value [ 0 , n ) [0, n) [0,n).

  • Similarly, we can prove that:

    For ANY position, the probability is 1 n \frac{1}{n} n1 for each value [ 0 , n ) [0, n) [0,n).

class Solution {private int[] array;private int[] original;Random rand = new Random();private int randRange(int min, int max) {return rand.nextInt(max - min) + min;}private void swapAt(int i, int j) {int temp = array[i];array[i] = array[j];array[j] = temp;}public Solution(int[] nums) {array = nums;original = nums.clone();}public int[] reset() {array = original;original = original.clone();return original;}public int[] shuffle() {for (int i = 0; i < array.length; i++) {swapAt(i, randRange(i, array.length));}return array;}
}

Runtime: 77 ms, faster than 70.11% of Java online submissions for Shuffle an Array.

Memory Usage: 50.8 MB, less than 100.00% of Java online submissions for Shuffle an Array.

class Solution {vector<int> nums;
public:Solution(vector<int> nums) {this->nums = nums;}/** Resets the array to its original configuration and return it. */vector<int> reset() {return nums;}/** Returns a random shuffling of the array. */vector<int> shuffle() {vector<int> result(nums);for (int i = 0;i < result.size();i++) {int pos = rand()%(result.size()-i);swap(result[i+pos], result[i]);}return result;}
};

Runtime: 204 ms, faster than 75.73% of C++ online submissions for Shuffle an Array.

Memory Usage: 30.2 MB, less than 71.43% of C++ online submissions for Shuffle an Array.

Complexity Analysis

  • Time complexity : O ( n ) O(n) O(n)

    Go through all element of arrays and generate a random index before the current element and swapping the current element and the random element

  • Space complexity : O ( n ) O(n) O(n)

    Because we need to use linear additional space to store the original array for reset operation

Summary

1. Random Value

  • java

    private int randRange(int min, int max) { // [min, max) left-opened right-closedreturn rand.nextInt(max - min) + min;}
    
  • cpp

            for (int i = 0;i < result.size();i++) {int pos = rand()%(result.size()-i);swap(result[i+pos], result[i]);}
    

2. Re-emphasize: [left-opened right-closed)

3. Shuffle Method

这篇关于384. Shuffle an Array的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/890422

相关文章

【uva】11536-Smallest Sub-Array(区间移动问题)

一个区间移动的问题,1A了,感觉没什么好说的。。 13975926 11536 Smallest Sub-Array Accepted C++ 0.809 2014-08-01 11:00:20 #include<cstdio>#include<cstring>#include<iostream>using namespace std;#define INF 1 << 30

leetCode#448. Find All Numbers Disappeared in an Array

Description Given an array of integers where 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once. Find all the elements of [1, n] inclusive that do not appear in this

做一个问卷考试,标准答案对比用户填写的答案,array_diff 进行差集比对

if( empty(array_diff($answer_mark, $answer)) && empty(array_diff( $answer,$answer_mark))){//用户答题正确}else{// 答题错误} 做一个问卷考试,标准答案对比用户填写的答案,array_diff  进行差集比对   如用户填写的答案变量为answer   标准答案为answer_mark

Spark学习之路 (十)SparkCore的调优之Shuffle调优

《2021年最新版大数据面试题全面开启更新》 欢迎关注github《大数据成神之路》 目录 一、概述 二、shuffle的定义 三、ShuffleManager发展概述 四、HashShuffleManager的运行原理 4.1 未经优化的HashShuffleManager 4.2 优化后的HashShuffleManager 五、SortShuffleManager运行原理 5.1 普通

【硬刚Hadoop】HADOOP MAPREDUCE(7):Shuffle机制(3)

本文是对《【硬刚大数据之学习路线篇】从零到大数据专家的学习指南(全面升级版)》的Hadoop部分补充。 7 Combiner合并 (6)自定义Combiner实现步骤 (a)自定义一个Combiner继承Reducer,重写Reduce方法 public class WordcountCombiner extends Reducer<Text, IntWritable, Text,

【硬刚Hadoop】HADOOP MAPREDUCE(6):Shuffle机制(2)

本文是对《【硬刚大数据之学习路线篇】从零到大数据专家的学习指南(全面升级版)》的Hadoop部分补充。 4 WritableComparable排序 1.排序的分类 2.自定义排序WritableComparable (1)原理分析 bean对象做为key传输,需要实现WritableComp

【硬刚Hadoop】HADOOP MAPREDUCE(5):Shuffle机制(1)

本文是对《【硬刚大数据之学习路线篇】从零到大数据专家的学习指南(全面升级版)》的Hadoop部分补充。 1 Shuffle机制 Map方法之后,Reduce方法之前的数据处理过程称之为Shuffle。如图4-14所示。 2 Partition分区

Spark Shuffle FetchFailedException解决方案

在大规模数据处理中,这是个比较常见的错误。 报错提示 SparkSQL shuffle操作带来的报错 org.apache.spark.shuffle.MetadataFetchFailedException: Missing an output location for shuffle 0 org.apache.spark.shuffle.FetchFailedExcep

【Spark系列8】Spark Shuffle FetchFailedException报错解决方案

前半部分来源:http://blog.csdn.net/lsshlsw/article/details/51213610 后半部分是我的优化方案供大家参考。 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ SparkSQL shuffle操作带来的报

浅谈MapReduce核心之shuffle

Hadoop拥有三大核心组件,HDFS作为底层的分布式文件系统,MapReduce作为计算框架,yarn作为资源调度管理器。 对于开发人员来说,理解MapReduce是很重要的。 在WordCount程序中,map生成的结果是一个个的元组,类似于(hello,1),非常非常多的元组,由context写入到hdfs中,而后续的Reduce阶段,实际上reduce方法接收的参数类似于这种,(hel