1. 程式人生 > >leetcode簡單題101-120(python)

leetcode簡單題101-120(python)

455. Assign Cookies(e-101)

Assume you are an awesome parent and want to give your children some cookies. But, you should give each child at most one cookie. Each child i has a greed factor gi, which is the minimum size of a cookie that the child will be content with; and each cookie j has a size sj. If sj >= gi, we can assign the cookie j to the child i, and the child i will be content. Your goal is to maximize the number of your content children and output the maximum number.

class Solution(object):
    def findContentChildren(self, g, s):
        """
        :type g: List[int]
        :type s: List[int]
        :rtype: int
        """
        g.sort()
        s.sort()
        i=0
        for cookie in s:
            if i >=len(g):
                break
            if g[i] <= cookie:
                i+=1
        return i

458. Poor Pigs(e-102)

There are 1000 buckets, one and only one of them contains poison, the rest are filled with water. They all look the same. If a pig drinks that poison it will die within 15 minutes. What is the minimum amount of pigs you need to figure out which bucket contains the poison within one hour.

Answer this question, and write an algorithm for the follow-up general case.

Follow-up:

If there are n buckets and a pig drinking poison will die within m minutes, how many pigs (x) you need to figure out the "poison" bucket within p minutes? There is exact one bucket with poison.

import math
class Solution(object):
    def poorPigs(self, buckets, minutesToDie, minutesToTest):
        """
        :type buckets: int
        :type minutesToDie: int
        :type minutesToTest: int
        :rtype: int
        """
        time=minutesToTest/minutesToDie + 1
        res=0
        while math.pow(time, res) < buckets:
            res+=1
        return res

459. Repeated Substring Pattern(e-103)

Given a non-empty string check if it can be constructed by taking a substring of it and appending multiple copies of the substring together. You may assume the given string consists of lowercase English letters only and its length will not exceed 10000.

class Solution(object):
    def repeatedSubstringPattern(self, s):
        """
        :type s: str
        :rtype: bool
        """
        for i in range(0, len(s)/2):
            if not len(s)%(i+1) and s[:i+1] * (len(s)/(i+1)) == s:
                return True
        return False

461. Hamming Distance(e-104)

The Hamming distance between two integers is the number of positions at which the corresponding bits are different.

Given two integers x and y, calculate the Hamming distance.

class Solution(object):
    def hammingDistance(self, x, y):
        """
        :type x: int
        :type y: int
        :rtype: int
        """
        x = x ^ y
        y = 0
        while x:
            y += 1
            x = x & (x - 1)
        return y

463. Island Perimeter(e-105)

You are given a map in form of a two-dimensional integer grid where 1 represents land and 0 represents water. Grid cells are connected horizontally/vertically (not diagonally). The grid is completely surrounded by water, and there is exactly one island (i.e., one or more connected land cells). The island doesn't have "lakes" (water inside that isn't connected to the water around the island). One cell is a square with side length 1. The grid is rectangular, width and height don't exceed 100. Determine the perimeter of the island.

class Solution(object):
    def islandPerimeter(self, grid):
        """
        :type grid: List[List[int]]
        :rtype: int
        """
        def helper(grid, i, j):
            res = 0
            if grid[i][j] == 0:
                return 0
            if i == 0 or i - 1 >= 0 and grid[i - 1][j] == 0:
                res += 1
            if i == len(grid) - 1 or i + 1 < len(grid) and grid[i + 1][j] == 0:
                res += 1
            if j == 0 or j - 1 >= 0 and grid[i][j - 1] == 0:
                res += 1
            if j == len(grid[0]) - 1 or j + 1 < len(grid[0]) and grid[i][j + 1] == 0:
                res += 1
            return res
            
        ans = 0
        for i in xrange(0, len(grid)):
            for j in xrange(0, len(grid[0])):
                ans += helper(grid, i, j)
        return ans

475. Heaters(e-106)----------------

Winter is coming! Your first job during the contest is to design a standard heater with fixed warm radius to warm all the houses.

Now, you are given positions of houses and heaters on a horizontal line, find out minimum radius of heaters so that all houses could be covered by those heaters.

So, your input will be the positions of houses and heaters seperately, and your expected output will be the minimum radius standard of heaters.

Note:

  1. Numbers of houses and heaters you are given are non-negative and will not exceed 25000.
  2. Positions of houses and heaters you are given are non-negative and will not exceed 10^9.
  3. As long as a house is in the heaters' warm radius range, it can be warmed.
  4. All the heaters follow your radius standard and the warm radius will the same.

476. Number Complement(e-107)------------

Given a positive integer, output its complement number. The complement strategy is to flip the bits of its binary representation.

Note:

  1. The given integer is guaranteed to fit within the range of a 32-bit signed integer.
  2. You could assume no leading zero bit in the integer’s binary representation.
class Solution(object):
    def findComplement(self, num):
        i = 1
        while i <= num:
            i = i << 1
        return (i - 1) ^ num

479. Largest Palindrome Product(e-108)

Find the largest palindrome made from the product of two n-digit numbers.

Since the result could be very large, you should return the largest palindrome mod 1337.

class Solution(object):
    def largestPalindrome(self, n):
        """
        :type n: int
        :rtype: int
        """
        return [9, 9009, 906609, 99000099, 9966006699, 999000000999, \
                    99956644665999, 9999000000009999][n - 1] % 1337

482. License Key Formatting(e-109)

You are given a license key represented as a string S which consists only alphanumeric character and dashes. The string is separated into N+1 groups by N dashes.

Given a number K, we would want to reformat the strings such that each group contains exactly K characters, except for the first group which could be shorter than K, but still must contain at least one character. Furthermore, there must be a dash inserted between two groups and all lowercase letters should be converted to uppercase.

Given a non-empty string S and a number K, format the string according to the rules described above.

class Solution(object):
    def licenseKeyFormatting(self, S, K):
        """
        :type S: str
        :type K: int
        :rtype: str
        """
        s=S.split("-")
        s="".join(s)
        n=len(s)
        start=n%K
        res=[]
        if start !=0:
            res.append(s[:start].upper())
        for k in range(0,(len(s)-start)/K):
            res.append(s[start:start+K].upper())
            start+=K
        return "-".join(res)
        

485. Max Consecutive Ones(e-110)

Given a binary array, find the maximum number of consecutive 1s in this array.

class Solution(object):
    def findMaxConsecutiveOnes(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        ans=0
        count=0
        for num in nums:
            if num ==1:
                count+=1
            else:
                count=0
            ans=max(ans, count)
        return ans

492. Construct the Rectangle(e-111)

For a web developer, it is very important to know how to design a web page's size. So, given a specific rectangular web page’s area, your job by now is to design a rectangular web page, whose length L and width W satisfy the following requirements:

1. The area of the rectangular web page you designed must equal to the given target area.

2. The width W should not be larger than the length L, which means L >= W.

3. The difference between length L and width W should be as small as possible.

You need to output the length L and the width W of the web page you designed in sequence.

class Solution(object):
    def constructRectangle(self, area):
        """
        :type area: int
        :rtype: List[int]
        """
        root=int(area**0.5)
        while root>0:
            if area%root==0:
                return int(area/root), root
            else:
                root-=1
        

496. Next Greater Element I(e-112)----------

You are given two arrays (without duplicates) nums1 and nums2 where nums1’s elements are subset of nums2. Find all the next greater numbers for nums1's elements in the corresponding places of nums2.

The Next Greater Number of a number x in nums1 is the first greater number to its right in nums2. If it does not exist, output -1 for this number.

500. Keyboard Row(e-113)

Given a List of words, return the words that can be typed using letters of alphabet on only one row's of American keyboard like the image below.

class Solution(object):
    def findWords(self, words):
        """
        :type words: List[str]
        :rtype: List[str]
        """
        ans=[]
        d={}
        row1="qwertyuiop"
        row2="asdfghjkl"
        row3="zxcvbnm"
        for r in row1:
            d[r]=1.0
        for r in row2:
            d[r]=2.0
        for r in row3:
            d[r]=3.0
        for word in words:
            same=True
            pre=d[word[0].lower()]
            for c in word:
                if pre!=d[c.lower()]:
                    same=False
                    break
                pre=d[c.lower()]
            if same:
                ans.append(word)
        return ans
            
        

501. Find Mode in Binary Search Tree(e-114)---------

Given a binary search tree (BST) with duplicates, find all the mode(s) (the most frequently occurred element) in the given BST.

Assume a BST is defined as follows:

  • The left subtree of a node contains only nodes with keys less than or equal to the node's key.
  • The right subtree of a node contains only nodes with keys greater than or equal to the node's key.
  • Both the left and right subtrees must also be binary search trees.

 

For example:
Given BST [1,null,2,2],

   1
    \
     2
    /
   2

 

return [2].

504. Base 7(e-115)

Given an integer, return its base 7 string representation.

class Solution(object):
    def convertToBase7(self, num):
        """
        :type num: int
        :rtype: str
        """
        if not num:
            return '0'
        ans=[]
        sgn='-' if num<0 else ''
        num=abs(num)
        while num:
            ans.append(str(num%7))
            num/=7
        return sgn+''.join(ans[::-1])
        

506. Relative Ranks(e-116)

Given scores of N athletes, find their relative ranks and the people with the top three highest scores, who will be awarded medals: "Gold Medal", "Silver Medal" and "Bronze Medal".

507. Perfect Number(e-117)

We define the Perfect Number is a positive integer that is equal to the sum of all its positive divisors except itself.

Now, given an integer n, write a function that returns true when it is a perfect number and false when it is not.

class Solution(object):
    def checkPerfectNumber(self, num):
        """
        :type num: int
        :rtype: bool
        """
        ans=1
        div=2
        while div**2 <= num:
            if num%div==0:
                ans+=div
                ans+=num/div
            div+=1
        return ans==num if num!=1 else False

520. Detect Capital(e-118)

Given a word, you need to judge whether the usage of capitals in it is right or not.

We define the usage of capitals in a word to be right when one of the following cases holds:

  1. All letters in this word are capitals, like "USA".
  2. All letters in this word are not capitals, like "leetcode".
  3. Only the first letter in this word is capital if it has more than one letter, like "Google".

Otherwise, we define that this word doesn't use capitals in a right way.

class Solution(object):
    def detectCapitalUse(self, word):
        """
        :type word: str
        :rtype: bool
        """
        return word.upper()==word or word.lower()==word or word.title()==word

521. Longest Uncommon Subsequence I(e-119)

Given a group of two strings, you need to find the longest uncommon subsequence of this group of two strings. The longest uncommon subsequence is defined as the longest subsequence of one of these strings and this subsequence should not be any subsequence of the other strings.

subsequence is a sequence that can be derived from one sequence by deleting some characters without changing the order of the remaining elements. Trivially, any string is a subsequence of itself and an empty string is a subsequence of any string.

The input will be two strings, and the output needs to be the length of the longest uncommon subsequence. If the longest uncommon subsequence doesn't exist, return -1.

class Solution(object):
    def findLUSlength(self, a, b):
        """
        :type a: str
        :type b: str
        :rtype: int
        """
        return max(len(a), len(b)) if a!=b else -1
        

530. Minimum Absolute Difference in BST(e-120)------

Given a binary search tree with non-negative values, find the minimum absolute difference between values of any two nodes.