File tree Expand file tree Collapse file tree 2 files changed +28
-46
lines changed
Expand file tree Collapse file tree 2 files changed +28
-46
lines changed Original file line number Diff line number Diff line change 11class Solution {
2- public static int [] shortestToChar (String S , char C ) {
3- int [] ans = new int [S .length ()];
4-
5- int count = (int ) S .chars ().filter (ch -> ch == C ).count ();
6-
7- int [] Cindexes = new int [count ];
8- int [] indexes = new int [S .length ()];
9-
10- int i = 0 ;
11-
12- for (int j =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 (int j =0 ; j <S .length (); j ++) {
21- ans [j ] = findMin (Cindexes , indexes [j ]);
22- }
23-
24- return ans ;
2+ public int [] shortestToChar (String S , char C ) {
3+ int [] ans = new int [S .length ()];
4+ int prev = Integer .MIN_VALUE / 2 ;
5+ for (int i = 0 ; i < S .length (); i ++) {
6+ if (S .charAt (i ) == C ) {
7+ prev = i ;
8+ }
9+ ans [i ] = i - prev ;
2510 }
26-
27- private static int findMin (int [] cindexes , int i ) {
28- int minDist = Integer .MAX_VALUE ;
29-
30- for (int index : cindexes ) {
31- minDist = Math .min (minDist , Math .abs (index - i ));
32- }
33-
34- return minDist ;
35- }
11+ prev = Integer .MAX_VALUE / 2 ;
12+ for (int i = 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+ return ans ;
19+ }
3620}
Original file line number Diff line number Diff line change 11class Solution {
2- public int subarraySum (int [] nums , int k ) {
3- Map <Integer , Integer > map = new HashMap <>();
4- map .put (0 , 1 );
5- int count = 0 ;
6- int currentSum = 0 ;
7-
8- for (int num : nums ) {
9- currentSum += num ;
10- count += map .getOrDefault (currentSum - k , 0 );
11- map .put (currentSum , map .getOrDefault (currentSum , 0 ) + 1 );
12- }
13-
14- return count ;
2+ public int subarraySum (int [] nums , int k ) {
3+ int sum = 0 ;
4+ int count = 0 ;
5+ Map <Integer , Integer > map = new HashMap <>();
6+ map .put (0 , 1 );
7+ for (int i = 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+ return count ;
13+ }
1614}
You can’t perform that action at this time.
0 commit comments