プログラミング練習-アルゴリズム関連

 LeetCodeでプログラミングの練習をしているので、その一部のメモ。

1)Add to Numbers(足し算)

Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

You can return the answer in any order.

 

Example 1:

Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].

Example 2:

Input: nums = [3,2,4], target = 6
Output: [1,2]

Example 3:

Input: nums = [3,3], target = 6
Output: [0,1]

方針

  • 配列要素のインデックスを返したい。変数の合計値がTargetであること。
  • ハッシュマップを使用してインデックスを格納する
  • 配列をFor文で回す
  • enumerateでインデックスと変数値にする
  • 最初の要素から開始して、指定された配列内の各要素を反復処理
  • 各反復で、必要な数 (必要な数 = ターゲットの合計 - 現在の数) がハッシュマップに存在するかどうかを確認
  • 存在する場合は、{必要な番号インデックス、現在の番号インデックス} を結果として返す

コード

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        history = {}
        for i, num in enumerate(nums):
            if num in history:
                return [i,history[num]]
            else:
                history[target-num]=i



2)palindrome (逆数)

Given an integer x, return true if x is palindrome integer.

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

  • For example, 121 is a palindrome while 123 is not.

 

Example 1:

Input: x = 121
Output: true
Explanation: 121 reads as 121 from left to right and from right to left.

Example 2:

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

方針

  • 数値をStringに変換する
  • Stringの最初の数と最後の数がマッチするか確認する
  • マッチした場合はTrueを返す

コード

class Solution(object):

    def isPalindrome(self, x):

        """

        :type x: int

        :rtype: bool

        """

        s = str(x)

        rs = s[::-1]

        print(rs)

        if rs == s:

            return True

Next Post Previous Post
No Comment
Add Comment
comment url