- Notifications
You must be signed in to change notification settings - Fork 123
Expand file tree
/
Copy pathMinimumSizeSubarraySum209.java
More file actions
Latest commit
90 lines (76 loc) · 2.48 KB
/
Copy pathMinimumSizeSubarraySum209.java
File metadata and controls
90 lines (76 loc) · 2.48 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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
/**
* Given an array of n positive integers and a positive integer s, find the
* minimal length of a contiguous subarray of which the sum ≥ s. If there isn't
* one, return 0 instead.
*
* For example, given the array [2,3,1,2,4,3] and s = 7,
* the subarray [4,3] has the minimal length under the problem constraint.
*
* More practice:
* If you have figured out the O(n) solution, try coding another solution of
* which the time complexity is O(n log n).
*
*/
publicclassMinimumSizeSubarraySum209 {
publicintminSubArrayLen(ints, int[] nums) {
if (nums == null || nums.length == 0 || s == 0) return0;
intslow = 0;
intsum = 0;
intmin = Integer.MAX_VALUE;
for (intfast=0; fast<nums.length; fast++) {
sum += nums[fast];
while (sum >= s && slow < nums.length) {
min = Math.min(min, fast-slow+1);
sum -= nums[slow];
slow++;
}
}
returnmin == Integer.MAX_VALUE ? 0 : min;
}
publicintminSubArrayLen2(ints, int[] nums) {
if (nums == null || nums.length == 0) return0;
intminLen = Integer.MAX_VALUE;
intsum = 0;
intleft = 0;
intright = 0;
while (right < nums.length) {
sum += nums[right++];
while (sum >= s) {
if (right - left < minLen) {
minLen = right - left;
}
sum -= nums[left++];
}
}
returnminLen == Integer.MAX_VALUE ? 0 : minLen;
}
publicintminSubArrayLen3(ints, int[] nums) {
if (nums == null || nums.length == 0) return0;
intlo = 1;
inthi = nums.length;
intminLen = Integer.MAX_VALUE;
while (lo <= hi) {
intmid = lo + (hi - lo) / 2;
if (isValid(nums, mid, s)) {
if (mid < minLen) minLen = mid;
hi = mid - 1;
} else {
lo = mid + 1;
}
}
returnminLen == Integer.MAX_VALUE ? 0 : minLen;
}
privatebooleanisValid(int[] nums, intlen, ints) {
intsum = 0;
for (inti=0; i<len; i++) {
sum += nums[i];
if (sum >= s) returntrue;
}
for (inti=len; i<nums.length; i++) {
sum -= nums[i-len];
sum += nums[i];
if (sum >= s) returntrue;
}
returnfalse;
}
}