摘要:

  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:

  1. pattern = "abba", str = "dog cat cat dog" should return true.
  2. pattern = "abba", str = "dog cat cat fish" should return false.
  3. pattern = "aaaa", str = "dog cat cat dog" should return false.
  4. 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:

  1. You must do this in-place without making a copy of the array.
  2. 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)的更多相关文章

  1. LeetCode(275)H-Index II

    题目 Follow up for H-Index: What if the citations array is sorted in ascending order? Could you optimi ...

  2. LeetCode(220) Contains Duplicate III

    题目 Given an array of integers, find out whether there are two distinct indices i and j in the array ...

  3. LeetCode(154) Find Minimum in Rotated Sorted Array II

    题目 Follow up for "Find Minimum in Rotated Sorted Array": What if duplicates are allowed? W ...

  4. 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 ...

  5. LeetCode(116) Populating Next Right Pointers in Each Node

    题目 Given a binary tree struct TreeLinkNode { TreeLinkNode *left; TreeLinkNode *right; TreeLinkNode * ...

  6. 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 ...

  7. 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 ...

  8. 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 ...

  9. Leetcode(1)两数之和

    Leetcode(1)两数之和 [题目表述]: 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标.你可以假设每种输入只会对应一 ...

  10. Leetcode(2)两数相加

    Leetcode(2)两数相加 [题目表述]: 给出两个 非空 的链表用来表示两个非负的整数.其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字. 如果,我们将这两 ...

随机推荐

  1. springmvc 标签

    https://www.baeldung.com/spring-mvc-form-tags     1. Overview In the first article of this series we ...

  2. POJ - 3662 Telephone Lines (Dijkstra+二分)

    题意:一张带权无向图中,有K条边可以免费修建.现在要修建一条从点1到点N的路,费用是除掉免费的K条边外,权值最大的那条边的值,求最小花费. 分析:假设存在一个临界值X,小于X的边全部免费,那么此时由大 ...

  3. nodejs多核处理

    前言大家都知道nodejs是一个单进程单线程的服务器引擎,不管有多么的强大硬件,只能利用到单个CPU进行计算.所以,有人开发了第三方的cluster,让node可以利用多核CPU实现并行. 随着nod ...

  4. boot空间不足,删除Ubuntu旧内核

    0 Problem 今天打开电脑的时候ubuntu提示boot空间不足.查了资料,原来Ubuntu的自动升级并没有删除系统的旧内核,于是boot下旧的内核文件越积越多,最后就满了. 1 Solutio ...

  5. 如何修改Django中的日期和时间格式 DateTimeField

    html页面从数据库中读出DateTimeField字段时,显示的时间格式和数据库中存放的格式不一致,比如数据库字段内容为2017-06-03 13:00:00,但是页面显示的却是Apr. 03, 2 ...

  6. C++结构体定义和C的区别

    对于C来说,struct定义的结构体不是一种数据类型,所以每次声明的时候需要加上struct让编译器知道这是结构体,为了不每次都加上struct关键字,可以在定义结构体的时候加上typedef关键字: ...

  7. LeetCode——Number Complement

    LeetCode--Number Complement Question Given a positive integer, output its complement number. The com ...

  8. LeetCode——Number of Boomerangs

    LeetCode--Number of Boomerangs Question Given n points in the plane that are all pairwise distinct, ...

  9. javascript onclick 函数不执行

    今天被这个问题搞伤了. 原本是要给table中的元素添加onclick事件处理函数,刚开始还可以,后来就不行了,百试不得其解,反复检查,程序也没问题,耗了一个多小时,偏偏我就不信电脑会扯拐,就要看看还 ...

  10. WPF中关于配置文件的读取

    在WPF中的配置文件的读取也是经常用到的一个操作,虽然很基础,但是也记录一下,以后忘记了可以看一看. 首先就是先新建一个Application Configuration Flie后缀名是.confi ...