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 = ;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
这就是我这几天看的五个算法的实现,当然修正了各种版本在此也就不加赘述。对于算法有更好实现的朋友还望不吝赐教~
LeetCode — (1)的更多相关文章
- LeetCode(275)H-Index II
题目 Follow up for H-Index: What if the citations array is sorted in ascending order? Could you optimi ...
- LeetCode(220) Contains Duplicate III
题目 Given an array of integers, find out whether there are two distinct indices i and j in the array ...
- LeetCode(154) Find Minimum in Rotated Sorted Array II
题目 Follow up for "Find Minimum in Rotated Sorted Array": What if duplicates are allowed? W ...
- LeetCode(122) Best Time to Buy and Sell Stock II
题目 Say you have an array for which the ith element is the price of a given stock on day i. Design an ...
- LeetCode(116) Populating Next Right Pointers in Each Node
题目 Given a binary tree struct TreeLinkNode { TreeLinkNode *left; TreeLinkNode *right; TreeLinkNode * ...
- LeetCode(113) Path Sum II
题目 Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given ...
- LeetCode(107) Binary Tree Level Order Traversal II
题目 Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from l ...
- LeetCode(4)Median of Two Sorted Arrays
题目 There are two sorted arrays nums1 and nums2 of size m and n respectively. Find the median of the ...
- Leetcode(1)两数之和
Leetcode(1)两数之和 [题目表述]: 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标.你可以假设每种输入只会对应一 ...
- Leetcode(2)两数相加
Leetcode(2)两数相加 [题目表述]: 给出两个 非空 的链表用来表示两个非负的整数.其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字. 如果,我们将这两 ...
随机推荐
- Kattis - pizzahawaii 【状态标记】
Kattis - pizzahawaii [状态标记] Description You are travelling in a foreign country. Although you are al ...
- Sublime Text 3 快捷键 一览
Sublime Text 3 快捷键精华版 Ctrl+Shift+P:打开命令面板 Ctrl+P:搜索项目中的文件 Ctrl+G:跳转到第几行 Ctrl+W:关闭当前打开文件 Ctrl+Shift+W ...
- datagrid 编辑
spark:DataGrid编辑状态进入需要在选中一行高亮状态之后,再次点击该单元格,这样,相信非常符合开发人员的控制手法及大众使用习惯,这,是一点非常好的改良. 同时,它取缔了itemEditEnd ...
- MySQL-5.7创建及查看数据库
1.创建数据库语句 create database语句是在MySQL实例上创建一个指定名称的数据库. create schema语句的语义和create database是一样的. 2.语法解析 CR ...
- No module named bz2
yum install bzip* python2.6 import bz2 python2.7 import bz2 error 解决:sudo cp /usr/lib64/python2.6/li ...
- 优先队列 STL (转)
优先队列是队列的一种,不过它可以按照自定义的一种方式(数据的优先级)来对队列中的数据进行动态的排序每次的push和pop操作,队列都会动态的调整,以达到我们预期的方式来存储. 例如:我们常用的操作就是 ...
- ARM协处理器CP15寄存器详解【转】
本文转载i自;https://blog.csdn.net/gameit/article/details/13169405 用于系统存储管理的协处理器CP15 MCR{cond} copro ...
- try catch finally中return的执行顺序
下面说一下try{ } catch{}中有return的情况 究竟是哪个return起作用的 话不多说 上代码 1 try中有return的情况 //普通方法 public static int hh ...
- 深入理解MR1与MR2的执行流程
摘自:Tom White ,<Hadoop.The.Definitive.Guide.3rd.Edition> MR1 MR2
- DateTime和DateTimeOffset的区别
1,DateTime 表示时间上的一刻,通常以日期和当天时间来表示. 2, DateTimeOffset 表示一个时间点,通常以相对于协调世界时(UTC)的日期和时间来表示. 3,下面是微软官方给出的 ...