teratail header banner
teratail header banner
質問するログイン新規登録

回答編集履歴

2

微修正

2020/04/30 07:03

投稿

episteme
episteme

スコア16612

answer CHANGED
@@ -32,10 +32,7 @@
32
32
  break;
33
33
  }
34
34
 
35
- if(!flag) {
36
- ans = new int[1]; ans[0] = -1;
35
+ return flag ? ans : new int[]{-1};
37
- }
38
- return ans;
39
36
  }
40
37
 
41
38
  public static void main(String[] args) {

1

追記

2020/04/30 07:03

投稿

episteme
episteme

スコア16612

answer CHANGED
@@ -4,4 +4,53 @@
4
4
 
5
5
  > 戻す値がint[]なので、最初からansをint[]で書きたい
6
6
 
7
- return ans.toArray()
7
+ return ans.toArray()
8
+
9
+ [追記] バグみっけ。
10
+ ```Java
11
+ import java.util.*;
12
+
13
+ public class Trial {
14
+
15
+ static int[] absolutePermutation(int n, int k) {
16
+ Set<Integer> used = new HashSet<Integer>();
17
+ boolean flag = true;
18
+ int[] ans = new int[n];
19
+
20
+ for(int i=1; i<=n; i++) {
21
+ if ( i-k >= 1 && !used.contains(i-k) ){
22
+ used.add(i-k);
23
+ ans[i-1]= i-k; // ココと
24
+ continue;
25
+ }
26
+ if( i+k <= n && !used.contains(i+k) ){
27
+ used.add(i+k);
28
+ ans[i-1]= i+k; // ココ
29
+ continue;
30
+ }
31
+ flag = false;
32
+ break;
33
+ }
34
+
35
+ if(!flag) {
36
+ ans = new int[1]; ans[0] = -1;
37
+ }
38
+ return ans;
39
+ }
40
+
41
+ public static void main(String[] args) {
42
+ for ( int item : absolutePermutation(2, 1) ) {
43
+ System.out.printf("%d ", item);
44
+ }
45
+ System.out.println();
46
+ for ( int item : absolutePermutation(3, 0) ) {
47
+ System.out.printf("%d ", item);
48
+ }
49
+ System.out.println();
50
+ for ( int item : absolutePermutation(3, 2) ) {
51
+ System.out.printf("%d ", item);
52
+ }
53
+ System.out.println();
54
+ }
55
+ }
56
+ ```