File tree 1 file changed +39
-35
lines changed
src/main/java/com/fishercoder/solutions 1 file changed +39
-35
lines changed Original file line number Diff line number Diff line change 30
30
*/
31
31
public class _481 {
32
32
33
- /**credit: https://discuss.leetcode.com/topic/74917/simple-java-solution-using-one-array-and-two-pointers
34
- * Algorithm:
35
-
36
- 1. Create an int array a and initialize the first 3 elements with 1, 2, 2.
37
- 2. Create two pointers head and tail. head points to the number which will be used to generate new numbers.
38
- tail points to the next empty position to put the new number. Then keep generating new numbers until tail >= n.
39
- 3. Need to create the array 1 element more than n to avoid overflow because the last round head might points to a number 2.
40
- 4. A trick to flip number back and forth between 1 and 2: num = num ^ 3*/
41
- public int magicalString (int n ) {
42
- if (n <= 0 ) {
43
- return 0 ;
44
- }
45
- if (n <= 3 ) {
46
- return 1 ;
47
- }
33
+ public static class Solution1 {
34
+ /**
35
+ * credit: https://discuss.leetcode.com/topic/74917/simple-java-solution-using-one-array-and-two-pointers
36
+ * Algorithm:
37
+ *
38
+ * 1. Create an int array a and initialize the first 3 elements with 1, 2, 2.
39
+ * 2. Create two pointers head and tail. head points to the number which will be used to generate new numbers.
40
+ * tail points to the next empty position to put the new number. Then keep generating new numbers until tail >= n.
41
+ * 3. Need to create the array 1 element more than n to avoid overflow because the last round head might points to a number 2.
42
+ * 4. A trick to flip number back and forth between 1 and 2: num = num ^ 3
43
+ */
44
+ public int magicalString (int n ) {
45
+ if (n <= 0 ) {
46
+ return 0 ;
47
+ }
48
+ if (n <= 3 ) {
49
+ return 1 ;
50
+ }
48
51
49
- int [] a = new int [n + 1 ];
50
- a [0 ] = 1 ;
51
- a [1 ] = 2 ;
52
- a [2 ] = 2 ;
53
-
54
- int head = 2 ;
55
- int tail = 3 ;
56
- int num = 1 ;
57
- int result = 1 ;
58
-
59
- while (tail < n ) {
60
- for (int i = 0 ; i < a [head ]; i ++) {
61
- a [tail ] = num ;
62
- if (num == 1 && tail < n ) {
63
- result ++;
52
+ int [] a = new int [n + 1 ];
53
+ a [0 ] = 1 ;
54
+ a [1 ] = 2 ;
55
+ a [2 ] = 2 ;
56
+
57
+ int head = 2 ;
58
+ int tail = 3 ;
59
+ int num = 1 ;
60
+ int result = 1 ;
61
+
62
+ while (tail < n ) {
63
+ for (int i = 0 ; i < a [head ]; i ++) {
64
+ a [tail ] = num ;
65
+ if (num == 1 && tail < n ) {
66
+ result ++;
67
+ }
68
+ tail ++;
64
69
}
65
- tail ++;
70
+ num = num ^ 3 ;
71
+ head ++;
66
72
}
67
- num = num ^ 3 ;
68
- head ++;
69
- }
70
73
71
- return result ;
74
+ return result ;
75
+ }
72
76
}
73
77
74
78
}
You can’t perform that action at this time.
0 commit comments