-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
2 changed files
with
81 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,55 @@ | ||
# 148. 排序链表 | ||
|
||
给你链表的头结点 head ,请将其按 升序 排列并返回 排序后的链表 。 | ||
|
||
<https://leetcode-cn.com/problems/sort-list/> | ||
|
||
```js | ||
/** | ||
* Definition for singly-linked list. | ||
* function ListNode(val, next) { | ||
* this.val = (val===undefined ? 0 : val) | ||
* this.next = (next===undefined ? null : next) | ||
* } | ||
*/ | ||
/** | ||
* @param {ListNode} head | ||
* @return {ListNode} | ||
*/ | ||
var sortList = function(head) { | ||
if (!head || !head.next) return head | ||
|
||
var slow = fast = head | ||
while (fast.next && fast.next.next) { | ||
slow = slow.next | ||
fast = fast.next.next | ||
} | ||
var temp = slow.next | ||
slow.next = null | ||
slow = temp | ||
|
||
return merge(sortList(head), sortList(slow)) | ||
}; | ||
|
||
// LC21 | ||
var merge = function(l1, l2) { | ||
const pre = new ListNode(-1) | ||
let current = pre | ||
while(l1 !== null && l2 !== null) { | ||
if (l1.val > l2.val) { | ||
current.next = l2 | ||
l2 = l2.next | ||
} else { | ||
current.next = l1 | ||
l1 = l1.next | ||
} | ||
current = current.next | ||
} | ||
if (l1 === null) { | ||
current.next = l2 | ||
} else { | ||
current.next = l1 | ||
} | ||
return pre.next | ||
}; | ||
``` |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,26 @@ | ||
# 152. 乘积最大子数组 | ||
|
||
给你一个整数数组 nums ,请你找出数组中乘积最大的连续子数组(该子数组中至少包含一个数字),并返回该子数组所对应的乘积。 | ||
|
||
<https://leetcode-cn.com/problems/maximum-product-subarray/> | ||
|
||
--- | ||
|
||
```js | ||
/** | ||
* @param {number[]} nums | ||
* @return {number} | ||
*/ | ||
var maxProduct = function(nums) { | ||
var min = max = result = nums[0] | ||
for (var i = 1; i < nums.length; i ++) { | ||
|
||
var minTemp = min, maxTemp = max | ||
|
||
min = Math.min(nums[i] * maxTemp, nums[i], nums[i] * minTemp) | ||
max = Math.max(nums[i] * minTemp, nums[i], nums[i] * maxTemp) | ||
result = Math.max(result, max) | ||
} | ||
return result | ||
}; | ||
``` |