• 【LeetCode每天一题】Palindrome Number( 回文数字)


    Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.

    Example 1:          Input: 121            Output: true

    Example 2:          Input: -121          Output: false                Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.

    Example 3:         Input: 10              Output: false                Explanation: Reads 01 from right to left. Therefore it is not a palindrome.

    Follow up: Coud you solve it without converting the integer to a string?

    思路


          这道题最简单的解决办法是将数字转换成字符串,从头和尾向中间进行遍历。可以得出结果。但是在题中给出了可不可以不适用转化字符的办法来解决。这里我想到了使用辅助空间来解决。 申请一个堆和队列。然后依此将数字加入其中。然后再逐个对比数字是否相等。相等则时回文。时间复杂度为O(log 10 n), 空间复杂度为O(n).

    图示步骤


             

    实现代码


      

     1 class Solution(object):
     2     def isPalindrome(self, x):
     3         """
     4         :type x: int
     5         :rtype: bool
     6         """
     7         if x < 0:                  # 如果数字小于0,直接返回
     8             return False
     9         tem1, tem2 = [], []      # 设置两个辅助列表来模拟栈和队列。
    10         while x:                  # 堆数字进行遍历
    11             tem = x %10
    12             tem1.append(tem)
    13             tem2.append(tem)
    14             x //= 10
    15         i, end = 0, len(tem1)-1     
    16         while i < len(tem1) and end >= 0:  # 队列和栈来依此访问。
    17             if tem1[i] != tem2[end]:
    18                 return False             # 有一个不相等直接返回。
    19             i += 1
    20             end -= 1
    21         return True

     

  • 相关阅读:
    js怪招(摘录篇)
    猪八戒实习笔记(工具总结)
    2014年最新前端开发面试题(面霸题库)
    经典算法:快排的Javascript版本
    IE的CSS相关的BUG(整理一)
    setTimeout()的返回值
    面试回忆录(三)
    面试回忆录(二)
    读取指定文件夹下的全部文件,可通过正则进行过滤,返回文件路径数组 -- 基于node的一个函数
    Backbone简单示例
  • 原文地址:https://www.cnblogs.com/GoodRnne/p/10638543.html
Copyright © 2020-2023  润新知