Skip to content

Commit d0fcbd1

Browse files
Add java solution to LC775
1 parent 3cfeaf2 commit d0fcbd1

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
/*
2+
We have some permutation A of [0, 1, ..., N - 1], where N is the
3+
length of A.
4+
5+
The number of (global) inversions is the number of i < j with
6+
0 <= i < j < N and A[i] > A[j].
7+
8+
The number of local inversions is the number of i with 0 <= i < N
9+
and A[i] > A[i+1].
10+
11+
Return true if and only if the number of global inversions is equal
12+
to the number of local inversions.
13+
14+
Example 1:
15+
Input: A = [1,0,2]
16+
Output: true
17+
Explanation: There is 1 global inversion, and 1 local inversion.
18+
19+
Example 2:
20+
Input: A = [1,2,0]
21+
Output: false
22+
Explanation: There are 2 global inversions, and 1 local inversion.
23+
Note:
24+
25+
A will be a permutation of [0, 1, ..., A.length - 1].
26+
A will have length in range [1, 5000].
27+
The time limit for this problem has been reduced.
28+
*/
29+
30+
class Solution {
31+
public boolean isIdealPermutation(int[] A) {
32+
int i = 0;
33+
while (i + 1 < A.length){
34+
if ((A[i] != i) && (A[i] != i+1)){
35+
return false;
36+
} else if ((A[i] == i+1) && (A[i+1] != i)){
37+
return false;
38+
} else if (A[i] == i+1){
39+
i++;
40+
}
41+
i++;
42+
}
43+
return true;
44+
}
45+
}

0 commit comments

Comments
 (0)