Js 源码
题目
215. Kth Largest Element in an Array
Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element.
Example 1:
Input: [3,2,1,5,6,4] and k = 2 Output: 5
Example 2:
Input: [3,2,3,1,2,4,5,5,6] and k = 4 Output: 4
Note: You may assume k is always valid, 1 ≤ k ≤ array's length.
思考路程
1 直接排序,再输出就ok了
56. Merge Intervals
Given a collection of intervals, merge all overlapping intervals.
Example 1:
Input: intervals = [[1,3],[2,6],[8,10],[15,18]] Output: [[1,6],[8,10],[15,18]] Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6].
Example 2:
Input: intervals = [[1,4],[4,5]] Output: [[1,5]] Explanation: Intervals [1,4] and [4,5] are considered overlapping.
NOTE: input types have been changed on April 15, 2019. Please reset to default code definition to get new method signature.
Constraints:
intervals[i][0] <= intervals[i][1]
思考路程
1 直接合并
57. Insert Interval
Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary).
You may assume that the intervals were initially sorted according to their start times.
Example 1:
Input: intervals = [[1,3],[6,9]], newInterval = [2,5] Output: [[1,5],[6,9]]
Example 2:
Input: intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]], newInterval = [4,8] Output: [[1,2],[3,10],[12,16]] Explanation: Because the new interval [4,8] overlaps with [3,5],[6,7],[8,10].
NOTE: input types have been changed on April 15, 2019. Please reset to default code definition to get new method signature.
思考路程
1 直接使用56的合并即可
147. Insertion Sort List
Sort a linked list using insertion sort.
A graphical example of insertion sort. The partial sorted list (black) initially contains only the first element in the list. With each iteration one element (red) is removed from the input data and inserted in-place into the sorted list
Algorithm of Insertion Sort:
Insertion sort iterates, consuming one input element each repetition, and growing a sorted output list.
At each iteration, insertion sort removes one element from the input data, finds the location it belongs within the sorted list, and inserts it there.
It repeats until no input elements remain.
Example 1:
Input: 4->2->1->3 Output: 1->2->3->4
Example 2:
Input: -1->5->3->4->0 Output: -1->0->3->4->5
思考路程
1 就是类似插入法排序,新建一个链表,不断的在新链表中插入就可以了。
148. Sort List
Sort a linked list in O(n log n) time using constant space complexity.
Example 1:
Input: 4->2->1->3 Output: 1->2->3->4
Example 2:
Input: -1->5->3->4->0 Output: -1->0->3->4->5
思考路程
1 直接使用147代码
164. Maximum Gap
Given an unsorted array, find the maximum difference between the successive elements in its sorted form.
Return 0 if the array contains less than 2 elements.
Example 1:
Input: [3,6,9,1] Output: 3 Explanation: The sorted form of the array is [1,3,6,9], either (3,6) or (6,9) has the maximum difference 3.
Example 2:
Input: [10] Output: 0 Explanation: The array contains less than 2 elements, therefore return 0.
Note:
You may assume all elements in the array are non-negative integers and fit in the 32-bit signed integer range.
Try to solve it in linear time/space
思考路程
1 如果不是 linear time/space , 应该很好做,先排序,然后再查找,算法时间复杂度是
O(nlgn)
2 如果要线性时间,我记得以前有个题目,是利用数组的下标来进行的。
3 题解
这里是用的类似桶排序的方法,桶排序有想到了,但是没有想到如何使用。
解法:
3.1 首先遍历一遍找到数组中最大和最下的值,max 和 min, 然后获得桶排序所必须的间隔值
let gap = Math.ceil((max - min) / (numsLen - 1));
这里为什么设置 gap 为这个值呢,因为从 min 到 max 走 n-1 步骤,每步加上 gap 刚好。
比如给出的数组是[3, 6, 9, 1], max = 9, min = 1;gap = 3;从 1 到 9 走 3 步,每步加 3,那就是 1, 4, 7, 10 刚好可以覆盖 1 到 9。
所以这里求的是最大的 maxgap 肯定不能小于 gap,因为如果每步加 gap,是刚刚好到达最大值,如果 maxgap 比刚刚好的 gap 的值还小,那么肯定是到达不了最大值的。
3.2 有了桶排序必须的 gap,然后就是建立 n-1 个桶,还是上面的[3, 6, 9, 1],这里建立 3 个桶,每个桶的的范围分别是[1,4], [4,7], [7,10]。
3.3 最后就是遍历桶,计算桶里的最大的 maxgap,然后再把每个桶里最大的和隔壁最小的值获取 maxgap,一直循环比较就得到了最大的 maxgap。
算法时间复杂度 O(n), 空间复杂度 O(n)
179. Largest Number
Given a list of non negative integers, arrange them such that they form the largest number.
Example 1:
Input: [10,2] Output: "210"
Example 2:
Input: [3,30,34,5,9] Output: "9534330"
Note: The result may be very large, so you need to return a string instead of an integer.
思考路程
1 根据单个数字进行排序,比如 34,转换成 3+4/2 = 3.5,所以排在 5 后边, 最后发现这边的逻辑好像是不对,比如
[1, 2, 30]
2 题解
2.1 可以利用字符传自带的比较,比如
var str1 = "ab";
var str2 = "ab";
var n = str1.localeCompare(str2);
直接对 nums 先转成字符串数组,然后再排序,然后再 join 输出即可 时间复杂度,假设平均字符串长度是 k,则排序加上 O(nlgn),则是 O(nklgn),空间复杂度为 O(1)
220. Contains Duplicate III
Given an array of integers, find out whether there are two distinct indices i and j in the array such that the absolute difference between nums[i] and nums[j] is at most t and the absolute difference between i and j is at most k.
Example 1:
Input: nums = [1,2,3,1], k = 3, t = 0 Output: true
Example 2:
Input: nums = [1,0,1,1], k = 1, t = 2 Output: true
Example 3:
Input: nums = [1,5,9,1,5,9], k = 2, t = 3 Output: false
思考路程
1 直接遍历就可以了
274. H-Index
Given an array of citations (each citation is a non-negative integer) of a researcher, write a function to compute the researcher's h-index.
According to the definition of h-index on Wikipedia: "A scientist has index h if h of his/her N papers have at least h citations each, and the other N − h papers have no more than h citations each."
Example:
Input: citations = [3,0,6,1,5] Output: 3 Explanation: [3,0,6,1,5] means the researcher has 5 papers in total and each of them had received 3, 0, 6, 1, 5 citations respectively. Since the researcher has 3 papers with at least 3 citations each and the remaining two with no more than 3 citations each, her h-index is 3.
Note: If there are several possible values for h, the maximum one is taken as the h-index.
思考路程
1 直接排序,然后取数组的值最后一个大于等于数组下标加1的最小值
算法时间复杂度O(nlgn) 空间复杂度O(1)
324. Wiggle Sort II
Given an unsorted array nums, reorder it such that nums[0] < nums[1] > nums[2] < nums[3]....
Example 1:
Input: nums = [1, 5, 1, 1, 6, 4] Output: One possible answer is [1, 4, 1, 5, 1, 6].
Example 2:
Input: nums = [1, 3, 2, 2, 3, 1] Output: One possible answer is [2, 3, 1, 3, 1, 2].
Note: You may assume all input has valid answer.
Follow Up: Can you do it in O(n) time and/or in-place with O(1) extra space?
思考路程
这里还是比较复杂的
1 首先找到数组中第mid个大小的数,方便划分数组,比如[1, 5, 1, 1, 6, 4],这里找到数组中第三大的数是1,所以根据题目的要求就是在奇数位放大于1的数,在偶数位放小于等于1的数。可以通过结果[1, 6, 1, 5, 1, 4]观察得出, 刚开始这里我想着先排序,然后倒序交换,发现遇到[1, 2, 2, 1, 2, 1, 1, 1, 1, 2, 2, 2]没法处理
2 既然明确了需要在奇数位放大于中间数的数字,在偶数位放小于中间数的数字,但是如何放呢?
发现题解里边用到了(1 + 2*index) % (n | 1),这里n为数组长度,可以通过分别设置index为0,1,2,3,4,5 得到1,3,5,0,2,4,这里可以理解为这些为虚拟下标。
然后就是不断的根据虚拟下标,把大于mid的数放到奇数位上,把小于的放到偶数位置上,中间数放到剩下的位置
例子。
输入数组[13,6,5,5,4,2], mid = 5
Mapped_idx[Left] 表示发现大于mid数的时候需要放置的位置
Mapped_idx[Right] 表示发现小于mid数的时候需要放置的位置
Step 1:
Original idx: 0 1 2 3 4 5
Mapped idx: 1 3 5 0 2 4 这里就是虚拟下标
Array: 13 6 5 5 4 2
Left 初始Left =0
i 初始i=0
Right 初始Right=5
当i=0的时候,nums[Mapped_idx[i]] = nums[1] = 6 > 5, so it is ok to put 6 in the first odd index 1. We increment i and left.
Step 2:
Original idx: 0 1 2 3 4 5
Mapped idx: 1 3 5 0 2 4
Array: 13 6 5 5 4 2
Left=1
i=1
Right=5
当i=1的时候,nums[Mapped_idx[i]] = nums[3] = 5 = 5, 因为5不大于mid. 所以下一次当发现大于mid的数字的时候,还是要放到Mapped_idx[1]=3的位置,所以只能i++, 继续往下去寻找.
Step 3:
Original idx: 0 1 2 3 4 5
Mapped idx: 1 3 5 0 2 4
Array: 13 6 5 5 4 2
Left=1
i=2
Right=5
当i=2的时候,nums[Mapped_idx[i]] = nums[5] = 2 < 5, so we want to put it to the last even index 4 (pointed by Right). So, we swap nums[Mapped_idx[i]] with nums[Mapped_idx[Right]], i.e. nums[5] with nums[4], and decrement Right. 因为这里发现了2小于5了,我们需要把2放到偶数位置上,也就是最后一个偶数位置,也就是,这里Right就是表示的最后一个偶数的位置,所以交换nums[Mapped_idx[i]] with nums[Mapped_idx[Right]],同时Right--;
Step 4:
Original idx: 0 1 2 3 4 5
Mapped idx: 1 3 5 0 2 4
Array: 13 6 5 5 2 4
Left=1
i=2
Right=4
i=2 ,因为上一步i的值没有改变,nums[5] = 4 < 5, so we want to put it to the second last even index 2. So, we swap nums[5] with nums[2], and decrement Right.
Step 5:
Original idx: 0 1 2 3 4 5
Mapped idx: 1 3 5 0 2 4
Array: 13 6 4 5 2 5
Left=1
i=2
Right=3
nums[5] = 5 === 5, it is ok to put it there, we increment i. 因为5 等于mid,不需要做什么,直接i++就可以
Step 6:
Original idx: 0 1 2 3 4 5
Mapped idx: 1 3 5 0 2 4
Array: 13 6 4 5 2 5
Left=1
i=3
Right=3
nums[0] = 13 > 5, so, we want to put it to the next odd index which is 3 (pointed by 'Left'). So, we swap nums[0] with nums[3], and increment 'Left' and 'i'.
Step Final:
Original idx: 0 1 2 3 4 5
Mapped idx: 1 3 5 0 2 4
Array: 5 6 4 13 2 5
Left=2
i=4
Right=3
i > Right, we get the final wiggle array 5 6 4 13 2 5 !
时间复杂度在找到中间数的实现,可以是O(n) ,空间复杂度O(1)
31. Next Permutation
Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.
If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).
The replacement must be in-place and use only constant extra memory.
Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.
1,2,3 → 1,3,2 3,2,1 → 1,2,3 1,1,5 → 1,5,1
思考过程
1 题目没怎么看懂,什么全排列,没看懂,
从 n 个不同元素中任取 m(m≤n)个元素,按照一定的顺序排列起来,叫做从 n 个不同元素中取出 m 个元素的一个排列。当 m=n 时所有的排列情况叫全排列。
字典序法
对给定的字符集中的字符规定了一个先后关系,在此基础上规定两个全排列的先后是从左到右逐个比较对应的字符的先后。
[例]字符集{1,2,3},较小的数字较先,
这样按字典序生成的全排列是:123,132,213,231,312,321。
[注意] 一个全排列可看做一个字符串,字符串可有前缀、后缀。
1)生成给定全排列的下一个排列 所谓一个的下一个就是这一个与下一个之间没有其他的。这就要求这一个与下一个有尽可能长的共同前缀,也即变化限制在尽可能短的后缀上。
[例]839647521 是 1--9 的排列。
1—9 的排列最前面的是 123456789,最后面的是 987654321,从右向左扫描若都是增的,就到 987654321,也就没有下一个了。否则找出第一次出现下降的位置。
这个让我想起了前面做的,利用两个字符串进行比较,从而排序的题目,下一个肯定是在最高位比前面的大一个,后面的是最小,比如 123,如果下一个肯定是把 2 和 3 一交换边恒 132,然后因为只有一个 2,肯定是最小的。
假如有 1243,则下一个肯定是 3 和 2 一交换得到 1342,但是明显 42 不是最小的,需要逆序,则达到 1324
时间复杂度 O(n), 空间复杂度 O(1)
堆排序
堆排序
1 堆排序是一个完全二叉树 2 1 个公式 parent = (i-1)/ 2 3 不断重构最大堆或者最小堆就可以了
const swap = (nums, i, j) => {
const temp = nums[j];
nums[j] = nums[i];
nums[i] = temp;
};
const heapfiy = (nums, index, maxIndex) => {
if (index >= maxIndex) return;
// 得到两个叶子的节点index
const leftLeafeIndex = 2 * index + 1;
const rightLeafIndex = 2 * index + 2;
let max = nums[index];
if (leftLeafeIndex <= maxIndex && nums[leftLeafeIndex] > max) {
max = nums[leftLeafeIndex];
swap(nums, index, leftLeafeIndex);
heapfiy(nums, leftLeafeIndex, maxIndex);
}
if (rightLeafIndex <= maxIndex && nums[rightLeafIndex] > max) {
max = nums[rightLeafIndex];
swap(nums, index, rightLeafIndex);
heapfiy(nums, rightLeafIndex, maxIndex);
}
};
const rebuildHeap = (nums, lastIndex) => {
if (nums[0] > nums[1] && nums[0] > nums[2]) {
return;
}
buildHeap(nums, lastIndex);
};
const buildHeap = (nums, len) => {
//从第一个不是叶子节点的节点开始循环
let firstChildIndex = Math.floor((len - 1) / 2);
for (let j = firstChildIndex; j >= 0; j--) {
heapfiy(nums, j, len);
}
};
function (nums) {
if (!nums || nums.length <= 1) return nums;
let last = nums.length - 1;
// 创建堆
buildHeap(nums, last);
// 不断的循环,把大顶堆的数字和最后一个元素交换
while (last > 0) {
console.log(nums, last);
swap(nums, 0, last);
last--;
if (last > 0) {
rebuildHeap(nums, last);
}
}
return nums;
};
349. Intersection of Two Arrays
Given two arrays, write a function to compute their intersection.
Example 1:
Input: nums1 = [1,2,2,1], nums2 = [2,2] Output: [2]
Example 2:
Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4] Output: [9,4]
Note:
Each element in the result must be unique.
The result can be in any order.
export default (nums1, nums2) => {
nums1.sort((a, b) => a - b);
nums2.sort((a, b) => a - b);
let minLenArr = nums2.length > nums1.length ? nums1 : nums2;
let maxLenArr = nums2.length > nums1.length ? nums2 : nums1;
let res = [];
let j = 0;
for (let i = 0; i < minLenArr.length; i++) {
if (maxLenArr.includes(minLenArr[i]) && !res.includes(minLenArr[i])) {
res.push(minLenArr[i]);
}
// while (j < maxLenArr.length) {
// if (maxLenArr[j] === minLenArr[i]) {
// res.push(minLenArr[i]);
// while (maxLenArr[j + 1] === maxLenArr[j]) {
// j++;
// }
// j++;
// } else {
// if (maxLenArr[j] > minLenArr[i]) {
// break;
// } else {
// j++;
// }
// }
// }
}
return res;
};
计数排序
应用范围有限,一般用于数组中都是正数,且重复数字比较多的数组
时间复杂度 O(n+k),空间复杂度 O(n+k)
export default (nums) => {
// 建立一个k数组,k记录nums数组中每个值出现的次数
let kArr = [];
for (let i = 0; i < nums.length; i++) {
if (!kArr[nums[i]]) {
kArr[nums[i]] = 0;
kArr[nums[i]]++;
} else {
kArr[nums[i]]++;
}
}
// 得到k数组中小于该数的数组
for (let j = 1; j < kArr.length; j++) {
if (!kArr[j - 1]) {
kArr[j - 1] = 0;
}
if (!kArr[j]) {
kArr[j] = 0;
}
kArr[j] += kArr[j - 1];
}
// 返回数组
let res = [];
// 取出来,然后放到合适的位置
for (let k = 0; k < nums.length; k++) {
res[kArr[nums[k]] - 1] = nums[k];
if (kArr[nums[k]] > 1) {
kArr[nums[k]]--;
}
}
// res.shift();
return res;
};
767. Reorganize String
Given a string S, check if the letters can be rearranged so that two characters that are adjacent to each other are not the same.
If possible, output any possible result. If not possible, return the empty string.
Example 1:
Input: S = "aab" Output: "aba"
Example 2:
Input: S = "aaab" Output: ""
Note:
S will consist of lowercase letters and have length in range [1, 500].
思考路程
1
count letter appearance and store in hash[i]
find the letter with largest occurence.
put the letter into even index numbe (0, 2, 4 ...) char array
put the rest into the array
We construct the resulting string in sequence: at position 0, 2, 4, ... and then 1, 3, 5, ...
In this way, we can make sure there is always a gap between the same characters
Consider this example: "aaabbbcdd", we will construct the string in this way:
a _ a _ a _ _ _ _ // fill in "a" at position 0, 2, 4
a b a _ a _ b _ b // fill in "b" at position 6, 8, 1
a b a c a _ b _ b // fill in "c" at position 3
a b a c a d b d b // fill in "d" at position 5, 7
这里为什么到8停止,因为8是字符串的最后一个位置。
算法复杂度O(n) 空间复杂度O(n+26) n是指最后结果使用的空间 26是存放字符和97的差值
心得:
1 这样放置字符,可以成为一个模板,涉及到字符串重排列的时候,根据位置放置
2 一个新的api String.fromCharCode
/**
* @param {string} S
* @return {string}
*/
export default (S) => {
let sHash = [];
// 找到字符每次出现的次数
for (let i = 0; i < S.length; i++) {
if (!sHash[S.charCodeAt(i) - 97]) {
sHash[S.charCodeAt(i) - 97] = 1;
} else {
sHash[S.charCodeAt(i) - 97]++;
}
}
let max = 0;
// 找到字符串中字符重复次数最多的,
for (let i = 0; i < sHash.length; i++) {
if (sHash[i] > max) {
max = sHash[i];
}
}
// 如果重复次数最多的字符,超过字符长度的一般,也就是说肯定会有重复的字符相邻
if (max > Math.floor((S.length + 1) / 2)) {
return "";
}
let res = [];
let len = sHash.length;
// 转成字符
for (let i = 0; i < len; i++) {
if (sHash[i]) {
sHash[i] = {
label: String.fromCharCode(i + 97),
count: sHash[i],
};
}
}
// 排序,必须先放置重复次数最多的
sHash.sort((a, b) => b.count - a.count);
let index = 0;
for (let j = 0; j < sHash.length; j++) {
while (sHash[j] && sHash[j].count > 0) {
res[index] = sHash[j].label;
sHash[j].count--;
index += 2;
if (index >= S.length) {
index = 1;
}
}
}
return res.join("");
};
621. Task Scheduler
You are given a char array representing tasks CPU need to do. It contains capital letters A to Z where each letter represents a different task. Tasks could be done without the original order of the array. Each task is done in one unit of time. For each unit of time, the CPU could complete either one task or just be idle.
However, there is a non-negative integer n that represents the cooldown period between two same tasks (the same letter in the array), that is that there must be at least n units of time between any two same tasks.
You need to return the least number of units of times that the CPU will take to finish all the given tasks.
Example 1:
Input: tasks = ["A","A","A","B","B","B"], n = 2 Output: 8 Explanation: A -> B -> idle -> A -> B -> idle -> A -> B There is at least 2 units of time between any two same tasks.
Example 2:
Input: tasks = ["A","A","A","B","B","B"], n = 0 Output: 6 Explanation: On this case any permutation of size 6 would work since n = 0. ["A","A","A","B","B","B"] ["A","B","A","B","A","B"] ["B","B","B","A","A","A"] ... And so on.
Example 3:
Input: tasks = ["A","A","A","A","A","A","B","C","D","E","F","G"], n = 2 Output: 16 Explanation: One possible solution is A -> B -> C -> A -> D -> E -> A -> F -> G -> A -> idle -> idle -> A -> idle -> idle -> A
Constraints:
The number of tasks is in the range [1, 10000].
The integer n is in the range [0, 100].
题解
/**
* @param {character[]} tasks
* @param {number} n
* @return {number}
*/
export default (tasks, n) => {
if (n <= 0) {
return tasks.length;
}
let sHash = new Array(26).fill(0);
// 找到字符每次出现的次数
for (let i = 0; i < tasks.length; i++) {
// A = 65
if (!sHash[tasks[i].charCodeAt(0) - 65]) {
sHash[tasks[i].charCodeAt(0) - 65] = 1;
} else {
sHash[tasks[i].charCodeAt(0) - 65]++;
}
}
sHash.sort((a, b) => a - b);
let i = 25;
// 找到出现次数最大的
while (i >= 0 && sHash[i] === sHash[25]) {
i--;
}
//(sHash[25] - 1) * (n + 1) 表示最大次数出现的
// sHash[25] - 1表示字符出现次数最多的次数
// (n + 1) 表示被出现次数分割的块数,比如AACCCDDEEE 3 则
// sHash[25] = C出现的次数3,n+1 是指 C和间隔3 加在一起的个数
// 25 - i 表示在和C出现的此时一样的字符个数
// 因为最小肯定是tasks的长度,所以要取最大数,一般出现这种情况是当sHash[25] - 1分成的各个块的时候,已经被插满了
//
return Math.max(tasks.length, (sHash[25] - 1) * (n + 1) + 25 - i);
};
1387. Sort Integers by The Power Value
The power of an integer x is defined as the number of steps needed to transform x into 1 using the following steps:
if x is even then x = x / 2
if x is odd then x = 3 * x + 1
For example, the power of x = 3 is 7 because 3 needs 7 steps to become 1 (3 --> 10 --> 5 --> 16 --> 8 --> 4 --> 2 --> 1).
Given three integers lo, hi and k. The task is to sort all integers in the interval [lo, hi] by the power value in ascending order, if two or more integers have the same power value sort them by ascending order.
Return the k-th integer in the range [lo, hi] sorted by the power value.
Notice that for any integer x (lo <= x <= hi) it is guaranteed that x will transform into 1 using these steps and that the power of x is will fit in 32 bit signed integer.
Example 1:
Input: lo = 12, hi = 15, k = 2 Output: 13 Explanation: The power of 12 is 9 (12 --> 6 --> 3 --> 10 --> 5 --> 16 --> 8 --> 4 --> 2 --> 1) The power of 13 is 9 The power of 14 is 17 The power of 15 is 17 The interval sorted by the power value [12,13,14,15]. For k = 2 answer is the second element which is 13. Notice that 12 and 13 have the same power value and we sorted them in ascending order. Same for 14 and 15.
Example 2:
Input: lo = 1, hi = 1, k = 1 Output: 1
Example 3:
Input: lo = 7, hi = 11, k = 4 Output: 7 Explanation: The power array corresponding to the interval [7, 8, 9, 10, 11] is [16, 3, 19, 6, 14]. The interval sorted by power is [8, 10, 11, 7, 9]. The fourth number in the sorted array is 7.
Example 4:
Input: lo = 10, hi = 20, k = 5 Output: 13
Example 5:
Input: lo = 1, hi = 1000, k = 777 Output: 570
Constraints:
1 <= lo <= hi <= 1000
1 <= k <= hi - lo + 1
/**
* @param {number} lo
* @param {number} hi
* @param {number} k
* @return {number}
*/
export default (lo, hi, k) => {
if (lo === hi) return lo;
let res = [];
for (let i = lo; i <= hi; i++) {
let count = i;
let number = 0;
while (count !== 1) {
if (count % 2 === 0) {
count = count / 2;
} else {
count = 3 * count + 1;
}
number++;
}
res.push({
label: i,
number,
});
}
res.sort((a, b) => a.number - b.number);
return res[k - 1].label;
};
2. Add Two Numbers
You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Example:
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 0 -> 8 Explanation: 342 + 465 = 807.
/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} l1
* @param {ListNode} l2
* @return {ListNode}
*/
// Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
// Output: 7 -> 0 -> 8
// Explanation: 342 + 465 = 807.
//
export default (l1, l2) => {
let c1 = l1;
let c2 = l2;
let sentinel = new ListNode(0);
let d = sentinel;
let sum = 0;
// 遍历
while (c1 !== null || c2 !== null) {
sum = Math.floor(sum / 10);
// 加上c1.val
if (c1 !== null) {
sum += c1.val;
c1 = c1.next;
}
// 加上c2.val
if (c2 !== null) {
sum += c2.val;
c2 = c2.next;
}
d.next = new ListNode(sum % 10);
d = d.next;
}
if (Math.floor(sum / 10) === 1) {
d.next = new ListNode(1);
}
return sentinel.next;
};