前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >LeetCode 刷题第二天

LeetCode 刷题第二天

作者头像
Innei
发布2021-12-28 11:48:28
1780
发布2021-12-28 11:48:28
举报
文章被收录于专栏:静之森

判断回文数

题目描述

代码语言:javascript
复制
1Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.

COPY

简要描述

判断回文数,经常做的。

实现

c

代码语言:javascript
复制
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

代码语言:javascript
复制
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

取两个数组的中位数

题目描述

代码语言:javascript
复制
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

代码语言:javascript
复制
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};
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019-07-23,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 判断回文数
    • 题目描述
      • 简要描述
        • 实现
        • 取两个数组的中位数
          • 题目描述
            • 简要描述
              • 思路
                • 实现
                领券
                问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档