摘要:python
Nim Game、WordPattern、Move zeros、First Bad version、Ugly Number五個算法的python實現。linux
一個月多沒更新,大概是由於狀態一直不太好吧,有幾回打開殊不知從何寫起。總結一下這一個月多:看了幾個算法;接觸了hadoop雖然還不算會;會用linux;看了HTML,JS;拿了兩個省獎,其中一個真是一直的夢想;加入了一個團隊也算是離本身的夢想更近一步;去過本身喜歡的地方;吃吃吃玩玩玩;作了好幾件本身喜歡的事;幫到了挺多人;此刻卻忽然糾結於考研仍是工做......其實想一想寫博客真的很棒,那麼從今天起仍是堅持常常寫了。不知道寫什麼,就寫LeetCode中本身最近看的算法吧~固然,仍是從最簡單的開始:算法
1.Nim Game數組
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.oop
For 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.this
題意:spa
你和朋友正在玩一個nim遊戲:輪流從一堆石子中每次去1-3顆,最後一個取完石子的勝,其中,假設你跟你的對手每次都能找到最佳策略(這和那個分寶石的遊戲很像有沒有)。要解決的問題是:給定一堆石子的個數n,判斷你的輸贏(輸爲False,贏爲True),其中,遊戲從你先開始。code
分析:blog
因爲每次都能找到最佳策略,那麼:當n 爲[1,3]時,你勢必會贏;當n爲4時,不論你第一次取幾個石子,你的朋友取到的石子個數均在[1,3],那麼你確定輸;同理,當n爲[5,7]時,你確定會取相應的石子將n轉換爲4,那麼你確定會贏;當n = 8時,不管你第一次取多少,留給你對手的石子個數都爲[5,7],你勢必輸....以此類推,當n爲4的倍數時,你確定會輸。
python實現:
學過C,C++,可是仍是想用pyhton。代碼以下:
class Solution(object): def canWinNim(self, n): """ :type n: int :rtype: bool """
return n % 4 != 0
2. wordpattern
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
.
Examples:
"abba"
, str = "dog cat cat dog"
should return true."abba"
, str = "dog cat cat fish"
should return false."aaaa"
, str = "dog cat cat dog"
should return false."abba"
, str = "dog dog dog dog"
should return false. 題意:
簡單的理解就是給出一組模式(pattern)和一個字符串(str),查看字符串是否與模式匹配。其中要注意的是:模式僅有小寫字母構成,字符串被單個空格字符隔開,字符串中每一個單詞都由小寫字母構成;模式和字符串的先後都不包含多餘的空格;模式中的每一個字母必須匹配一個字符串中長度至少爲1的單詞。
python代碼:
class Solution(object): def wordPattern(self, pattern, str): """ :type pattern: str :type str: str :rtype: bool """ words = str.split() if len(pattern) == len(words): return len(set(zip(pattern,words))) == len(set(pattern)) == len(set(words)) else: return False
3.Move Zeros
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.
For example, given nums = [0, 1, 0, 3, 12]
, after calling your function, nums
should be [1, 3, 12, 0, 0]
.
Note:
題意:
對於一個數組,編寫一個函數將全部數組中的0放在數組的末尾,並保持其它非0數組的相對位置不變,並保證不創建新的數組,儘可能減小運算量。
python代碼:
class Solution(object): def moveZeroes(self, nums): """ :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead. """ count = len(nums) p = 0 for i in range(0,count): if nums[i] != 0: nums[p] = nums[i] p = p + 1
for j in range(p,count): nums[j] = 0
4. First bad version
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.
題意:
能夠理解爲在一個排列有序的版本中找出第一個損壞的版本,其中第一個被損壞的版本以後的版本均被損壞。
分析:
查找,以前在C中編過相似程序,選取二分法。
python代碼:
class Solution(object): def firstBadVersion(self, n): """ :type n: int :rtype: int """ left,right = 1,n while(left <= right): mid = (left + right) / 2
if isBadVersion(mid): right = mid - 1
else: left = mid + 1
return left
5. Ugly number
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
. For example, 6, 8
are ugly while 14
is not ugly since it includes another prime factor 7
.
Note that 1
is typically treated as an ugly number.
題意:
編寫一個程序判斷一個數是否爲醜數。其中,醜數指的是隻包含因子2,3,5的數,1被當作是第一個醜數。
分析:
只能被2,3,5整除的數,那麼就是被2,3,5整除以後爲1,,據此能夠變成實現。首先想到的是C中的判斷質數的程序,以下:
#include<stdio.h> #include<conio.h>
void main(void) { int n,i; printf("please input a number:\n"); scanf("%d",&n); for(i = 2;i < n && n % i;i++) ; if (i >= n) printf("質數"); else printf("非質數"); getch(); }
質數是隻能被1和它自己整除的數,固然與上述程序仍是有必定差別的。
python實現:
class Solution(object): def isUgly(self, num): """ :type num: int :rtype: bool """
while(num >= 2 and num % 2 == 0): num /= 2; while(num >= 3 and num % 3 == 0): num /= 3; while(num >= 5 and num % 5 == 0): num /= 5; if(num == 1): return True else: return False
這就是我這幾天看的五個算法的實現,固然修正了各類版本在此也就不加贅述。對於算法有更好實現的朋友還望不吝賜教~