Movatterモバイル変換


[0]ホーム

URL:


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

Commitab92d04

Browse files
committed
Modified 2 solutions
1 parentf1fe4ef commitab92d04

File tree

2 files changed

+28
-46
lines changed

2 files changed

+28
-46
lines changed
Lines changed: 17 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -1,36 +1,20 @@
11
classSolution {
2-
publicstaticint[]shortestToChar(StringS,charC) {
3-
int[]ans =newint[S.length()];
4-
5-
intcount = (int)S.chars().filter(ch ->ch ==C).count();
6-
7-
int[]Cindexes =newint[count];
8-
int[]indexes =newint[S.length()];
9-
10-
inti =0;
11-
12-
for (intj=0;j<S.length();j++) {
13-
if (S.charAt(j) ==C) {
14-
Cindexes[i++] =j;
15-
}
16-
17-
indexes[j] =j;
18-
}
19-
20-
for (intj=0;j<S.length();j++) {
21-
ans[j] =findMin(Cindexes,indexes[j]);
22-
}
23-
24-
returnans;
2+
publicint[]shortestToChar(StringS,charC) {
3+
int[]ans =newint[S.length()];
4+
intprev =Integer.MIN_VALUE /2;
5+
for (inti =0;i <S.length();i++) {
6+
if (S.charAt(i) ==C) {
7+
prev =i;
8+
}
9+
ans[i] =i -prev;
2510
}
26-
27-
privatestaticintfindMin(int[]cindexes,inti) {
28-
intminDist =Integer.MAX_VALUE;
29-
30-
for (intindex :cindexes) {
31-
minDist =Math.min(minDist,Math.abs(index -i));
32-
}
33-
34-
returnminDist;
35-
}
11+
prev =Integer.MAX_VALUE /2;
12+
for (inti =S.length() -1;i >=0;i--) {
13+
if (S.charAt(i) ==C) {
14+
prev =i;
15+
}
16+
ans[i] =Math.min(ans[i],prev -i);
17+
}
18+
returnans;
19+
}
3620
}

‎Medium/Subarray Sum Equals K.java

Lines changed: 11 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,14 @@
11
classSolution {
2-
publicintsubarraySum(int[]nums,intk) {
3-
Map<Integer,Integer>map =newHashMap<>();
4-
map.put(0,1);
5-
intcount =0;
6-
intcurrentSum =0;
7-
8-
for (intnum :nums) {
9-
currentSum +=num;
10-
count +=map.getOrDefault(currentSum -k,0);
11-
map.put(currentSum,map.getOrDefault(currentSum,0) +1);
12-
}
13-
14-
returncount;
2+
publicintsubarraySum(int[]nums,intk) {
3+
intsum =0;
4+
intcount =0;
5+
Map<Integer,Integer>map =newHashMap<>();
6+
map.put(0,1);
7+
for (inti =0;i <nums.length;i++) {
8+
sum +=nums[i];
9+
count +=map.getOrDefault(sum -k,0);
10+
map.put(sum,map.getOrDefault(sum,0) +1);
1511
}
12+
returncount;
13+
}
1614
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp