1. 程式人生 > >leetcode簡單61-80(python)

leetcode簡單61-80(python)

242. Valid Anagram(e-61)

Given two strings s and , write a function to determine if t is an anagram of s.

class Solution(object):
    def isAnagram(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: bool
        """
        return sorted(s) == sorted(t)

257. Binary Tree Paths(e-62)

Given a binary tree, return all root-to-leaf paths.

Note: A leaf is a node with no children.

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def binaryTreePaths(self, root):
        """
        :type root: TreeNode
        :rtype: List[str]
        """
        res=[]
        if not root:
            return res
        if not root.left and not root.right:
            res.append(str(root.val))
        for path in self.binaryTreePaths(root.left):
            res.append(str(root.val) + '->' + path)
        for path in self.binaryTreePaths(root.right):
            res.append(str(root.val) + '->' + path)
        return res

258. Add Digits(e-63)

Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.

class Solution(object):
    def addDigits(self, num):
        """
        :type num: int
        :rtype: int
        """
        if num<10:
            return num
        else:
            return (1+(num-1)%9)
    

263. Ugly Number(e-64)

Write a program to check whether a given number is an ugly number.

Ugly numbers are positive numbers whose prime factors only include 2, 3, 5.

class Solution(object):
    def isUgly(self, n):
        """
        :type num: int
        :rtype: bool
        """
        if n <=0:
            return False
        while n%2==0 or n%3==0 or n%5==0:
            if n%2==0:
                n/=2
            if n%3 == 0:
                n/=3
            if n%5 == 0:
                n/=5
        if n == 1:
            return True
        return False
                

268. Missing Number(e-65)

Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array.

class Solution(object):
    def missingNumber(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        n=len(nums)
        return (n*(1+n)/2 - sum(nums))
            

278. First Bad Version(e-66)

You are a product manager and currently leading a team to develop a new product. Unfortunately, the latest version of your product fails the quality check. Since each version is developed based on the previous version, all the versions after a bad version are also bad.

Suppose you have n versions [1, 2, ..., n] and you want to find out the first bad one, which causes all the following ones to be bad.

You are given an API bool isBadVersion(version) which will return whether version is bad. Implement a function to find the first bad version. You should minimize the number of calls to the API.

# The isBadVersion API is already defined for you.
# @param version, an integer
# @return a bool
# def isBadVersion(version):

class Solution(object):
    def firstBadVersion(self, n):
        """
        :type n: int
        :rtype: int
        """
        #lo=1
        #hi=n
        #while lo<hi:
            #mid=(lo+hi)/2
            #if firstBadVersion(mid):
                #hi=mid
            #else:
                #lo=mid+1
        #return lo
        lo=1
        hi=n
        while True:
            mid=(lo+hi)/2
            if firstBadVersion(mid):
                if mid ==1 or firstBadVersion(m-1):
                    return mid
                else:
                    hi=mid-1
            else:
                lo=mid+1
            

283. Move Zeroes(e-67)

Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements.

class Solution(object):
    def moveZeroes(self, nums):
        """
        :type nums: List[int]
        :rtype: void Do not return anything, modify nums in-place instead.
        """
        i=0
        for num in nums:
            if num !=0:
                nums[i]=num
                i+=1
        for j in range(i,len(nums)):
            nums[j] = 0
            
        

290. Word Pattern(e-68)

Given a pattern and a string str, find if str follows the same pattern.

Here follow means a full match, such that there is a bijection between a letter in pattern and a non-empty word in str.

class Solution(object):
    def wordPattern(self, pattern, str):
        """
        :type pattern: str
        :type str: str
        :rtype: bool
        """
        words=str.split()
        if len(words) != len(pattern):
            return False
        return len(set(pattern)) == len(set(words)) == len(set(zip(pattern, words)))

292. Nim Game(e-69)

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.

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

303. Range Sum Query - Immutable(e-70)

Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive.

class NumArray(object):
    def __init__(self, nums):
        """
        initialize your data structure here.
        :type nums: List[int]
        """
        self.sums = [0] * (len(nums)+1)
        for i in xrange(len(nums)):
            self.sums[i+1] = self.sums[i] + nums[i]

    def sumRange(self, i, j):
        """
        sum of elements nums[i..j], inclusive.
        :type i: int
        :type j: int
        :rtype: int
        """
        return self.sums[j+1] - self.sums[i]

326. Power of Three(e-71)

Given an integer, write a function to determine if it is a power of three.

class Solution(object):
    def isPowerOfThree(self, n):
        """
        :type n: int
        :rtype: bool
        """
        return n>0 and 1162261467%n==0

342. Power of Four(e-72)

Given an integer (signed 32 bits), write a function to check whether it is a power of 4.

Example:
Given num = 16, return true. Given num = 5, return false.

class Solution(object):
   
    def isPowerOfFour(self, num):
        """
        :type num: int
        :rtype: bool
        """
        nums = [1, 4, 16, 64, 256, 1024, 4096, 16384, 65536, 262144, 1048576, 4194304, 16777216, 67108864, 268435456, 1073741824]
        return num in nums

344. Reverse String(e-73)

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

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

345. Reverse Vowels of a String(e-74)

Write a function that takes a string as input and reverse only the vowels of a string.

Example 1:
Given s = "hello", return "holle".

Example 2:
Given s = "leetcode", return "leotcede".

class Solution(object):
    def reverseVowels(self, s):
        """
        :type s: str
        :rtype: str
        """
        vowels = set(["a", "e", "i", "o", "u", "A", "E", "I", "O", "U"])
        s = list(s)
        start, end = 0, len(s) - 1
        while start < end:
            if s[start] not in vowels:
                start += 1
            elif s[end] not in vowels:
                end -= 1
            else:
                s[start], s[end] = s[end], s[start]
                start += 1
                end -= 1
        return "".join(s)

349. Intersection of Two Arrays(e-75)

Given two arrays, write a function to compute their intersection.

class Solution(object):
    def intersection(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: List[int]
        """
        return list(set(nums1) & set(nums2))

350. Intersection of Two Arrays II(e-76)

Given two arrays, write a function to compute their intersection.

class Solution(object):
    def intersect(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: List[int]
        """
        ans=[]
        nums1.sort()
        nums2.sort()
        i=j=0
        while i < len(nums1) and j < len(nums2):
            if nums1[i] == nums2[j]:
                ans.append(num1[i])
                i+=1
                j+=1
            elif nums1[i] <nums2[j]:
                i+=1
            elif nums1[i] > nums2[j]:
                j+=1
        return ans
                
            

367. Valid Perfect Square(e-77)

Given a positive integer num, write a function which returns True if num is a perfect square else False.

class Solution(object):
    def isPerfectSquare(self, num):
        """
        :type num: int
        :rtype: bool
        """
        lo=1
        hi=num
        if num==1:
            return True
        while lo<hi:
            mid=(lo+hi)/2
            if mid*mid == num:
                return True
            elif mid * mid <num:
                lo=mid+1
            elif mid * mid > num:
                hi=mid
        return False

371. Sum of Two Integers(e-78)-------------------

Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -.

Example:
Given a = 1 and b = 2, return 3.

class Solution(object):
    def getSum(self, a, b):
        """
        :type a: int
        :type b: int
        :rtype: int
        """
        while b != 0:
            carry = a & b
            a = (a ^ b) % 0x100000000
            b = (carry << 1) % 0x100000000
        return a if a <= 0x7FFFFFFF else a | (~0x100000000+1)

374. Guess Number Higher or Lower(e-79)

We are playing the Guess Game. The game is as follows:

I pick a number from 1 to n. You have to guess which number I picked.

Every time you guess wrong, I'll tell you whether the number is higher or lower.

You call a pre-defined API guess(int num) which returns 3 possible results (-11, or 0):

# The guess API is already defined for you.
# @param num, your guess
# @return -1 if my number is lower, 1 if my number is higher, otherwise return 0
# def guess(num):

class Solution(object):
    def guessNumber(self, n):
        """
        :type n: int
        :rtype: int
        """
        l, r = 1, n
        while l < r:
            m = l + (r - l)/2
            g = guess(m)
            if g == -1:
                r = m - 1
            elif g == 1:
                l = m + 1
            else:
                return m
        return l

383. Ransom Note(e-80)

Given an arbitrary ransom note string and another string containing letters from all the magazines, write a function that will return true if the ransom note can be constructed from the magazines ; otherwise, it will return false.

Each letter in the magazine string can only be used once in your ransom note.

Note:
You may assume that both strings contain only lowercase letters.

class Solution(object):
    def canConstruct(self, ransomNote, magazine):
        """
        :type ransomNote: str
        :type magazine: str
        :rtype: bool
        """
        
        for i in set(ransomNote):
            if magazine.count(i) < ransomNote.count(i):
                return False
        return True