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)两数相加 [题目表述]: 给出两个 非空 的链表用来表示两个非负的整数.其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字. 如果,我们将这两 ...
随机推荐
- Maven的Mirror和Repository
今天新公司入职,项目经理让迁出项目,心想maven的阿里镜像源挺快的,干脆在配置了公司私服之后自己配置了阿里的镜像源,没成想项目屡屡报错,找不到项目依赖的公司jar包,后来才发现,同事配置mirror ...
- PHP-FPM 慢执行日志、网站隔离配置
慢执行日志 1.配置文件下打开慢执行日志 vim /usr/local/php/etc/php-fpm.conf # 慢执行日志路径 slowlog = /path/to/slow.log # 设置超 ...
- 20145222 黄亚奇 《网络对抗》Exp8 Web基础
20145222 黄亚奇 <网络对抗>Exp8 Web基础 实践具体要求 (1).Web前端HTML(1分) 能正常安装.启停Apache.理解HTML,理解表单,理解GET与POST方法 ...
- Linux系统中使用netcat命令的奇技淫巧
netcat是网络工具中的瑞士军刀,它能通过TCP和UDP在网络中读写数据.通过与其他工具结合和重定向,你可以在脚本中以多种方式使用它.使用netcat命令所能完成的事情令人惊讶. netcat所做的 ...
- JUnit4 入门笔记
Test注解的两个可选参数 expected timeout The Test annotation supports two optional parameters. The first, expe ...
- MySQL二进制日志文件过期天数设置说明
今天在处理业务库中二进制文件的时候,想更改二进制文件的过期天数,发现日期如果设置成2位以上的整数.都会出现如下的警告.不能成功的设置过期日期天数.MySQL版本从5.1到5.5都是一样的. mysql ...
- ()IT 职场经验)一位10年Java工作经验的架构师的经验分享,感觉很受用。
阿里巴巴技术大牛黄勇的经验分享,感觉很受用. 关于IT 职场经验 1. 把技术当成工具 技术这东西,其实一点都不神秘,它只不过是一个工具,用这个工具可以帮助我们解决实际问题,就这么简单. 我们每天在面 ...
- EF Code-First 学习之旅 多对多的关系
public class Student { public Student() { this.Courses = new HashSet<Course>(); } public int S ...
- java官网下载
安装版 http://javadl.oracle.com/webapps/download/AutoDL?BundleId=234471_96a7b8442fe848ef90c96a2fad6ed6d ...
- 记一次Configured Capacity: 0 (0 B)的解决
场景 最近hadoop集群新加了一个节点N,通过Ambari管理 一切正常. 过了两天发现,虽然集群每天要进几个G的数据(共8个节点),但节点N占用空间丝毫没有变化,显然没有进数据啊 日志 查看该节点 ...