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)两数相加 [题目表述]: 给出两个 非空 的链表用来表示两个非负的整数.其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字. 如果,我们将这两 ...
随机推荐
- C++中的config设计
配置文件读写类,它要有以下这些方法: 1. 支持读入一个指定配置文件的能力 2. 支持随时加入一个配置项的能力 3. 足够强大,能够写入各种数据结构的配置信息 C++ 里,我们要存储这样的数据就使用 ...
- Python3,x:如何进行手机APP的数据爬取
Python3,x:如何进行手机APP的数据爬取 一.简介 平时我们的爬虫多是针对网页的,但是随着手机端APP应用数量的增多,相应的爬取需求也就越来越多,因此手机端APP的数据爬取对于一名爬虫工程师来 ...
- Nginx 301与302配置
说明 1.首先看一个完整代码示例,关于nginx 301 302跳转的. 301跳转设置: server { listen 80; server_name 123.com; rewrite ^/(.* ...
- VRChat简易教程1-开发环境准备(SDK)
原文:https://docs.vrchat.com/docs/setting-up-the-sdk 1 Unity 2017.4.15f1 下载地址https://download.unity3d. ...
- The revocation function was unable to check revocation for the certificate
https://stackoverflow.com/questions/45556189/git-the-revocation-function-was-unable-to-check-revocat ...
- quartz(2) -- 入门案例
第一步:添加jar,maven配置 <!-- quartz --> <dependency> <groupId>org.quartz-scheduler</g ...
- windchill系统——开发_角色管理——增加角色
步骤如下 ResourceBuild wt.project.RoleRB ant -f codebase/MakeJar.xml 这样就完成了,接下来看看结果
- nodejs 设计模式
1 . 单例模式 顾名思义,单例就是保证一个类只有一个实例,实现的方法是,先判断实例是否存在,如果存在则直接返回,若不存在,则创建实例对象,并将实例对象保存在静态变量中,当下次请求时,则可以直接返回这 ...
- QT treewidget 右键菜单
VS2012+QT5.2 ,没有ui,纯代码实现右键 方法一:常规但略麻烦 1.头文件slot中声明 QTreeWidget *tree; void showrightMenu(QPoint);//显 ...
- 给定字符串数组,用map的key保存数组中字符串元素,value保存字符串元素出现次数,最后统计个字符串元素出现次数
import java.util.HashMap; public class map1 { public static void main(String[] args) { String[] arra ...