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