File tree Expand file tree Collapse file tree 2 files changed +21
-41
lines changed Expand file tree Collapse file tree 2 files changed +21
-41
lines changed Original file line number Diff line number Diff line change 1
1
public class ProductOfArrayExceptSelf {
2
2
3
- // 耗时2ms
3
+ // 耗时1ms
4
+ /**
5
+ * 对于每个数,就是给其左边所有数乘一遍,再给其右边所有数乘一遍
6
+ */
4
7
public int [] productExceptSelf (int [] nums ) {
5
- if (nums .length == 0 ) {
6
- return null ;
8
+ int [] res = new int [nums .length ];
9
+ int left = 1 , right = 1 ;
10
+ for (int i = 0 ; i < nums .length ; i ++) {
11
+ res [i ] = left ;
12
+ left *= nums [i ];
7
13
}
8
- int [] result = new int [nums .length ];
9
- result [0 ] = 1 ;
10
- for (int i = 1 ; i < nums .length ; i ++) {
11
- result [i ] = nums [i - 1 ] * result [i - 1 ];
12
- }
13
- int right = 1 ;
14
14
for (int i = nums .length - 1 ; i >= 0 ; i --) {
15
- result [i ] *= right ;
15
+ res [i ] *= right ;
16
16
right *= nums [i ];
17
17
}
18
- return result ;
18
+ return res ;
19
19
}
20
20
}
Original file line number Diff line number Diff line change 2
2
3
3
public class Main {
4
4
5
- public ListNode mergeKLists (ListNode [] lists ) {
6
- return helper (lists , 0 , lists .length - 1 );
7
- }
8
-
9
- private ListNode helper (ListNode [] lists , int start , int end ) {
10
- if (start > end ) {
11
- return null ;
12
- }
13
- if (start == end ) {
14
- return lists [start ];
5
+ public int [] productExceptSelf (int [] nums ) {
6
+ int [] res = new int [nums .length ];
7
+ int left = 1 , right = 1 ;
8
+ for (int i = 0 ; i < nums .length ; i ++) {
9
+ res [i ] = left ;
10
+ left *= nums [i ];
15
11
}
16
- int mid = start + (end - start ) / 2 ;
17
- ListNode l1 = helper (lists , start , mid );
18
- ListNode l2 = helper (lists , mid + 1 , end );
19
- return mergeTwoLists (l1 , l2 );
20
- }
21
-
22
- public ListNode mergeTwoLists (ListNode l1 , ListNode l2 ) {
23
- ListNode dummy = new ListNode (0 );
24
- ListNode p = l1 , q = l2 , cur = dummy ;
25
- for ( ; p != null && q != null ; ) {
26
- if (p .val < q .val ) {
27
- cur .next = p ;
28
- p = p .next ;
29
- } else {
30
- cur .next = q ;
31
- q = q .next ;
32
- }
33
- cur = cur .next ;
12
+ for (int i = nums .length - 1 ; i >= 0 ; i --) {
13
+ res [i ] *= right ;
14
+ right *= nums [i ];
34
15
}
35
- cur .next = p != null ? p : q ;
36
- return dummy .next ;
16
+ return res ;
37
17
}
38
18
39
19
public static void main (String [] args ) {
You can’t perform that action at this time.
0 commit comments