-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathPlusOne.java
More file actions
52 lines (42 loc) · 1.13 KB
/
PlusOne.java
File metadata and controls
52 lines (42 loc) · 1.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package math;
import java.util.LinkedList;
import java.util.List;
/**
* Description: https://leetcode.com/problems/plus-one
* Difficulty: Easy
*/
public class PlusOne {
/**
* Time complexity: O(n)
* Space complexity: O(1)
*/
public int[] plusOneOptimalApproach(int[] digits) {
for (int i = digits.length - 1; i >= 0; i--) {
if (digits[i] < 9) {
digits[i] += 1;
return digits;
}
digits[i] = 0;
}
int[] result = new int[digits.length + 1];
result[0] = 1;
return result; // 100<...>0
}
/**
* Time complexity: O(n)
* Space complexity: O(n)
*/
public int[] plusOneNaiveApproach(int[] digits) {
List<Integer> result = new LinkedList<>();
int carry = 1; // plus one
for (int i = digits.length - 1; i >= 0; i--) {
int sum = digits[i] + carry;
result.add(0, sum % 10);
carry = sum / 10;
}
if (carry != 0) {
result.add(0, carry);
}
return result.stream().mapToInt(v -> v).toArray();
}
}