LeetCode — (1)
摘要:
Nim Game、WordPattern、Move zeros、First Bad version、Ugly Number五个算法的python实现。
一个月多没更新,大概是因为状态一直不太好吧,有几次打开却不知从何写起。总结一下这一个月多:看了几个算法;接触了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.
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.
题意:
你和朋友正在玩一个nim游戏:轮流从一堆石子中每次去1-3颗,最后一个取完石子的胜,其中,假设你跟你的对手每次都能找到最佳策略(这和那个分宝石的游戏很像有没有)。要解决的问题是:给定一堆石子的个数n,判断你的输赢(输为False,赢为True),其中,游戏从你先开始。
分析:
由于每次都能找到最佳策略,那么:当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:
- pattern =
"abba"
, str ="dog cat cat dog"
should return true. - pattern =
"abba"
, str ="dog cat cat fish"
should return false. - pattern =
"aaaa"
, str ="dog cat cat dog"
should return false. - pattern =
"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:
- You must do this in-place without making a copy of the array.
- Minimize the total number of operations.
题意:
对于一个数组,编写一个函数将所有数组中的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
这就是我这几天看的五个算法的实现,当然修正了各种版本在此也就不加赘述。对于算法有更好实现的朋友还望不吝赐教~