【LeetCode】Algorithm 1~10:1,7,9

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/roguesir/article/details/86670853

前言

本系列博客为平时刷LeetCode的记录,每十道题一篇博客,持续更新,所有代码详见GitHub:https://github.com/roguesir/LeetCode-Algorithm

1. Two Sum

Introduction

Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Example:

Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

Solution

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        res = {}
        for i in range(len(nums)):
            reduce_ = target - nums[i]
            if res.get(reduce_) is not None:
                return [i, res[reduce_]]
            res[nums[i]] = i
            

7. Reverse Integer

Introduction

Given a 32-bit signed integer, reverse digits of an integer.

Example 1:

Input: 123
Output: 321

Example 2:

Input: -123
Output: -321

Example 3:

Input: 120
Output: 21

Note:
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

Solution

class Solution(object):
    def reverse(self, x):
        """
        :type x: int
        :rtype: int
        """
        x = str(x)
        y = ""
        if x[0] == "-":
            y = y + x[0]
            for i in range(len(x)-1, 0, -1):
                y += x[i]
        else:
            for i in range(len(x)-1, -1, -1):
                y += x[i]
        if int(y) > 2**31-1 or int(y) < -2**31:
            return 0
        else:
            return int(y)

9. Palindrome Number

Introduction

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?

Solution

class Solution(object):
    def isPalindrome(self, x):
        """
        :type x: int
        :rtype: bool
        """
        x = str(x)
        out = True
        for i in range(len(x)/2):
            if x[i] == x[len(x)-1-i]:
                continue
            else:
                out = False
                break
        return out

https://leetcode.com/submissions/detail/202027004/

  • 更新时间:2019-01-27

猜你喜欢

转载自blog.csdn.net/roguesir/article/details/86670853