Skip to content

Commit 6380ca3

Browse files
add 634
1 parent 37297e4 commit 6380ca3

File tree

2 files changed

+32
-0
lines changed

2 files changed

+32
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ Your ideas/fixes/algorithms are more than welcome!
2020

2121
| # | Title | Solutions | Time | Space | Difficulty | Tag | Notes
2222
|-----|----------------|---------------|---------------|---------------|-------------|--------------|-----
23+
|634|[Find the Derangement of An Array](https://leetcode.com/problems/find-the-derangement-of-an-array/)|[Solution](../master/src/main/java/com/fishercoder/solutions/_634.java) | O(n) |O(1) | Medium | Math
2324
|633|[Sum of Square Numbers](https://leetcode.com/problems/sum-of-square-numbers/)|[Solution](../master/src/main/java/com/fishercoder/solutions/_633.java) | O(logn) |O(1) | Easy | Binary Search
2425
|628|[Maximum Product of Three Numbers](https://leetcode.com/problems/maximum-product-of-three-numbers/)|[Solution](../master/src/main/java/com/fishercoder/solutions/_628.java) | O(nlogn) |O(1) | Easy |
2526
|625|[Minimum Factorization](https://leetcode.com/problems/minimum-factorization/)|[Solution](../master/src/main/java/com/fishercoder/solutions/_625.java) | O(?) |O(?) | Medium |
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
package com.fishercoder.solutions;
2+
3+
/**
4+
* 634. Find the Derangement of An Array
5+
*
6+
* In combinatorial mathematics, a derangement is a permutation of the elements of a set, such that no element appears in its original position.
7+
8+
There's originally an array consisting of n integers from 1 to n in ascending order, you need to find the number of derangement it can generate.
9+
10+
Also, since the answer may be very large, you should return the output mod 109 + 7.
11+
12+
Example 1:
13+
Input: 3
14+
Output: 2
15+
Explanation: The original array is [1,2,3]. The two derangements are [2,3,1] and [3,1,2].
16+
17+
Note:
18+
n is in the range of [1, 106].
19+
*/
20+
public class _634 {
21+
/**reference: https://discuss.leetcode.com/topic/94442/java-5-lines-o-1-space-solution
22+
* and https://leetcode.com/articles/find-derangements/#approach-5-using-formula-accepted*/
23+
private static final int M = 1000000007;
24+
public int findDerangement(int n) {
25+
long ans = 1;
26+
for (int i = 1; i <= n; i++) {
27+
ans = (i * ans % M + (i%2 == 0 ? 1 : -1)) % M;
28+
}
29+
return (int) ans;
30+
}
31+
}

0 commit comments

Comments
 (0)