Algorithm

LeetCode - Suffle an Array

GREEN.1229 2021. 12. 13. 20:28

안녕하세요. 그린입니다🟢

이번 포스팅에서는 조금 쉬운 알고리즘을 하나 풀어볼까합니다.

어후 오늘 코딩이 잘 안되서 머리 깨울겸 하나 풀고 시작하려고해요🤯

이번에는 LeetCode에서 Suffle an Array라는 문제를 풀어봤어요!

 

문제제시

  • Given an integer array nums, design an algorithm to randomly shuffle the array. All permutations of the array should be equally likely as a result of the shuffling.
  • Implement the Solution class: 
    • Solution(int[] nums) Initializes the object with the integer array nums.
    • int[] reset() Resets the array to its original configuration and returns it.
    • int[] shuffle() Returns a random shuffling of the array.

Example 1:

Input
["Solution", "shuffle", "reset", "shuffle"]
[[[1, 2, 3]], [], [], []]
Output
[null, [3, 1, 2], [1, 2, 3], [1, 3, 2]]

Explanation
Solution solution = new Solution([1, 2, 3]);
solution.shuffle();    // Shuffle the array [1,2,3] and return its result.
                       // Any permutation of [1,2,3] must be equally likely to be returned.
                       // Example: return [3, 1, 2]
solution.reset();      // Resets the array back to its original configuration [1,2,3]. Return [1, 2, 3]
solution.shuffle();    // Returns the random shuffling of array [1,2,3]. Example: return [1, 3, 2]

Constraints:

  • 1 <= nums.length <= 200
  • -106 <= nums[i] <= 106
  • All the elements of nums are unique.
  • At most 5 * 104 calls in total will be made to reset and shuffle.

문제풀이

class Solution {
    var inputArray = [Int]()
    
    init(_ nums: [Int]) {
        self.inputArray = nums
    }
    
    func reset() -> [Int] {
        return inputArray
    }
    
    func shuffle() -> [Int] {
        var shuffledArray = inputArray
        shuffledArray.shuffle()
        
        return shuffledArray
    }
}

 

정말정말 간단합니다.초기값 init해주는 메서드와 reset 명령이 들어오면 초기값으로 바꿔주는 명령어그리고 shuffle 명령어 입력 시 무작위로 어레이를 섞어주는것 끝..끝...네! 코드도 너무 간단해서 설명은 스킵하겠습니다.오늘은 그냥 정말 머리식히는 커피같은 문제였어요☕️

 

풀이결과

마무리

아.. 이제 다시 코딩 해보러 가야겠습니다😭

 

[참고자료]

https://leetcode.com/problems/patching-array/submissions/

 

Patching Array - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com