Skip to content

Commit 8c6c516

Browse files
committed
fd
1 parent 0b43489 commit 8c6c516

File tree

2 files changed

+21
-41
lines changed

2 files changed

+21
-41
lines changed
Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,20 @@
11
public class ProductOfArrayExceptSelf {
22

3-
// 耗时2ms
3+
// 耗时1ms
4+
/**
5+
* 对于每个数,就是给其左边所有数乘一遍,再给其右边所有数乘一遍
6+
*/
47
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];
713
}
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;
1414
for (int i = nums.length - 1; i >= 0; i--) {
15-
result[i] *= right;
15+
res[i] *= right;
1616
right *= nums[i];
1717
}
18-
return result;
18+
return res;
1919
}
2020
}

leetcode/src/Main.java

Lines changed: 10 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -2,38 +2,18 @@
22

33
public class Main {
44

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];
1511
}
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];
3415
}
35-
cur.next = p != null ? p : q;
36-
return dummy.next;
16+
return res;
3717
}
3818

3919
public static void main(String[] args) {

0 commit comments

Comments
 (0)