Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit b5c1c7d

Browse files
committed
small sum
1 parent 5619ae0 commit b5c1c7d

File tree

1 file changed

+22
-30
lines changed

1 file changed

+22
-30
lines changed

‎src/main/java/grey/algorithm/Code_0024_NowCoder_SmallSum.java

Lines changed: 22 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -19,24 +19,15 @@ public class Code_0024_NowCoder_SmallSum {
1919
private static final int[] arr = new int[MAXN];
2020
private static final int[] help = new int[MAXN];
2121
private static int n;
22-
23-
public static void main(String[] args) throws IOException {
24-
try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) {
25-
StreamTokenizer in = new StreamTokenizer(br);
26-
try (PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out))) {
27-
in.nextToken();
28-
n = (int) in.nval;
29-
for (int i = 0; i < n; i++) {
30-
in.nextToken();
31-
arr[i] = (int) in.nval;
32-
}
33-
out.println(smallSum(0, n - 1));
34-
out.flush();
35-
}
22+
public static void main(String[] args) {
23+
Scanner in = new Scanner(System.in);
24+
n = in.nextInt();
25+
for (int i = 0; i < n; i++) {
26+
arr[i] = in.nextInt();
3627
}
28+
System.out.println(smallSum(0, n - 1));
3729
}
38-
39-
// 结果比较大,用int会溢出的,所以返回long类型
30+
// 结果比较大,用int会溢出的,所以返回long类型
4031
// 时间复杂度O(n * logn)
4132
public static long smallSum(int l, int r) {
4233
if (l == r) {
@@ -49,22 +40,22 @@ public static long smallSum(int l, int r) {
4940
// 返回跨左右产生的小和累加和,左侧有序、右侧有序,让左右两侧整体有序
5041
public static long merge(int l, int m, int r) {
5142
long ans = 0L;
52-
int i = l; // 卡左边界
53-
int j = m + 1; // 卡右边界
5443
long sum = 0L;
55-
while (j <= r) {
56-
// 滑动窗口,不回退
57-
while (i <= m && arr[i] <= arr[j]) {
58-
sum += arr[i++];
59-
}
60-
ans += sum;
61-
j++;
62-
}
6344
int s = l;
6445
int e = m + 1;
65-
i = l;
46+
while (e <= r) {
47+
while (s <= m && arr[s] <= arr[e]) {
48+
ans += arr[s++];
49+
}
50+
sum += ans;
51+
e++;
52+
}
53+
// help = new int[r - l + 1];
54+
s = l;
55+
e = m + 1;
56+
int i = 0;
6657
while (s <= m && e <= r) {
67-
if (arr[s] <= arr[e]) {
58+
if (arr[s] < arr[e]) {
6859
help[i++] = arr[s++];
6960
} else {
7061
help[i++] = arr[e++];
@@ -76,9 +67,10 @@ public static long merge(int l, int m, int r) {
7667
while (e <= r) {
7768
help[i++] = arr[e++];
7869
}
70+
int index = 0;
7971
for (i = l; i <= r; i++) {
80-
arr[i] = help[i];
72+
arr[i] = help[index++];
8173
}
82-
return ans;
74+
return sum;
8375
}
8476
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /