LeetCode 刷题第二天
判断回文数
题目描述
Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.
简要描述
判断回文数,经常做的。
实现
bool isPalindrome(int x){
if (x < 0) return false;
long long r = 0;long long t = x;
int temp;
while(x) {
temp = x % 10;
x /= 10;
r = r * 10 + temp;
}
return r == t? true : false;
}
Runtime: 8 ms, faster than 84.26% of C online submissions for Palindrome Number.
Memory Usage: 6.9 MB, less than 97.58% of C online submissions for Palindrome Number.
取两个数组的中位数
题目描述
There are two sorted arrays nums1 and nums2 of size m and n respectively.
Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).
You may assume nums1 and nums2 cannot be both empty.
Example 1:
nums1 = [1, 3]
nums2 = [2]
The median is 2.0
Example 2:
nums1 = [1, 2]
nums2 = [3, 4]
The median is (2 + 3)/2 = 2.5
简要描述
把两个数组合并后,取中位数。给出的两个数组已经排序过。
思路
最简单的方法,不适用其他自定义函数,使用原生 JS 数组中内置的 sort 方法。
注意 sort方法在使用的时候一定要注意,sort 默认的是字典排序,所以在排序负数的时候,负数不是从小到大的,所以要接受一个回调函数,自定义排序方法。
实现
const findMedianSortedArrays = function(nums1, nums2) {
const arr = [...nums1,...nums2].sort(function(a,b){return a-b;})
if (arr.length % 2) {
return arr[Math.floor(arr.length / 2)]
}
else {
return (arr[Math.floor(arr.length / 2)] + (arr[Math.floor(arr.length / 2) - 1]) ) /2
}
};