Leetcode Python Solution(continue update)

时间:2023-03-08 16:16:00
Leetcode Python Solution(continue update)

leetcode python solution

1. two sum (easy)

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.

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,

return [0, 1].

UPDATE (2016/2/13):

The return format had been changed to zero-based indices. Please read the above updated description carefully.

来源: https://leetcode.com/articles/two-sum/

solution
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
tmp_dict = {}
for i in range(len(nums)):
if target - nums[i] in tmp_dict:
return [tmp_dict[target - nums[i]], i]
else:
tmp_dict[nums[i]] = i

2. Reverse String (easy)

Write a function that takes a string as input and returns the string reversed.

Example:

Given s = "hello", return "olleh".

来源: https://leetcode.com/problems/reverse-string/

solution

class Solution(object): def reverseString(self, s): "" :type s: str :rtype: str """ return s[::-1]

3. Nim Game(easy)

You are playing the following Nim Game with your friend: There is a heap of stones on the table, each time one of you take turns to remove 1 to 3 stones. The one who removes the last stone will be the winner. You will take the first turn to remove the stones.

Both of you are very clever and have optimal strategies for the game. Write a function to determine whether you can win the game given the number of stones in the heap.

Example:

if there are 4 stones in the heap, then you will never win the game: no matter 1, 2, or 3 stones you remove, the last stone will always be removed by your friend.

来源: https://leetcode.com/problems/nim-game/

solution

class Solution(object): def canWinNim(self, n): """ :type n: int :rtype: bool """ return (n % 4 != 0)