Skip to content

Commit 8a18b2b

Browse files
refactor 908
1 parent d25be28 commit 8a18b2b

File tree

1 file changed

+22
-56
lines changed
  • src/main/java/com/fishercoder/solutions

1 file changed

+22
-56
lines changed

src/main/java/com/fishercoder/solutions/_908.java

+22-56
Original file line numberDiff line numberDiff line change
@@ -2,66 +2,32 @@
22

33
import java.util.Arrays;
44

5-
/**
6-
* 908. Smallest Range I
7-
*
8-
* Given an array A of integers, for each integer A[i] we may choose any x with -K <= x <= K, and add x to A[i].
9-
*
10-
* After this process, we have some array B.
11-
*
12-
* Return the smallest possible difference between the maximum value of B and the minimum value of B.
13-
*
14-
*
15-
*
16-
* Example 1:
17-
*
18-
* Input: A = [1], K = 0
19-
* Output: 0
20-
* Explanation: B = [1]
21-
* Example 2:
22-
*
23-
* Input: A = [0,10], K = 2
24-
* Output: 6
25-
* Explanation: B = [2,8]
26-
* Example 3:
27-
*
28-
* Input: A = [1,3,6], K = 3
29-
* Output: 0
30-
* Explanation: B = [3,3,3] or B = [4,4,4]
31-
*
32-
*
33-
* Note:
34-
*
35-
* 1 <= A.length <= 10000
36-
* 0 <= A[i] <= 10000
37-
* 0 <= K <= 10000
38-
*/
395
public class _908 {
406
public static class Solution1 {
417
public int smallestRangeI(int[] A, int K) {
42-
Arrays.sort(A);
43-
int smallestPlus = A[0] + K;
44-
int biggestMinus = A[A.length - 1] - K;
45-
int diff = biggestMinus - smallestPlus;
46-
if (diff > 0) {
47-
return diff;
48-
} else {
49-
return 0;
50-
}
51-
}
52-
}
8+
Arrays.sort(A);
9+
int smallestPlus = A[0] + K;
10+
int biggestMinus = A[A.length - 1] - K;
11+
int diff = biggestMinus - smallestPlus;
12+
if (diff > 0) {
13+
return diff;
14+
} else {
15+
return 0;
16+
}
17+
}
18+
}
5319

54-
public static class Solution2 {
55-
public int smallestRangeI(int[] A, int K) {
56-
int min = A[0];
57-
int max = A[0];
20+
public static class Solution2 {
21+
public int smallestRangeI(int[] A, int K) {
22+
int min = A[0];
23+
int max = A[0];
5824

59-
for (int k : A) {
60-
min = Math.min(min, k);
61-
max = Math.max(max, k);
62-
}
25+
for (int k : A) {
26+
min = Math.min(min, k);
27+
max = Math.max(max, k);
28+
}
6329

64-
return Math.max(max - min - 2 * K, 0);
65-
}
66-
}
30+
return Math.max(max - min - 2 * K, 0);
31+
}
32+
}
6733
}

0 commit comments

Comments
 (0)