2022-06-16

Description

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 <= 50

  • -10^6 <= nums[i] <= 10^6

  • All the elements of nums are unique.

  • At most 10^4 calls in total will be made to reset and shuffle.

Solution

Approach #0

Approach #1

Description

Write an algorithm to determine if a number n is happy.

A happy number is a number defined by the following process:

  • Starting with any positive integer, replace the number by the sum of the squares of its digits.

  • Repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1.

  • Those numbers for which this process ends in 1 are happy.

Return true if n is a happy number, and false if not.

Example 1:

Example 2:

Constraints:

  • 1 <= n <= 2^31 - 1

Solution

Approach #0: Fast ans slow pointer

Description

Given an array of points where points[i] = [xi, yi] represents a point on the X-Y plane, return the maximum number of points that lie on the same straight line.

Example 1:

Example 2:

Constraints:

  • 1 <= points.length <= 300

  • points[i].length == 2

  • -104 <= xi, yi <= 104

  • All the points are unique.

Solution

Approach #0

Description

Given an array of integers nums and an integer k, return the number of unique k-diff pairs in the array.

A k-diff pair is an integer pair (nums[i], nums[j]), where the following are true:

  • 0 <= i, j < nums.length

  • i != j

  • nums[i] - nums[j] == k

Notice that |val| denotes the absolute value of val.

Example 1:

Example 2:

Example 3:

Constraints:

  • 1 <= nums.length <= 10^4

  • -10^7 <= nums[i] <= 10^7

  • 0 <= k <= 10^7

Solution

Approach #0

Last updated