别着急,坐和放宽
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
}
};
判断回文数:给定一个整数,判断其是否为回文数(即正着读和反着读都一样的数字)。实现时通常可把数字转为字符串,前后对称比较。
合并两个已排序数组取中位数:把两个已排序数组合并,排序,然后找到中位数。注意用sort时要传入比较函数(如a-b),避免默认的字典序问题,尤其涉及负数。