2019独角兽企业重金招聘Python工程师标准>>>

本文不断更新中

----------------------------------------

2018.3.20

9. Palindrome Number

Determine whether an integer is a palindrome. Do this without extra space.

Could negative integers be palindromes? (ie, -1)

If you are thinking of converting the integer to string, note the restriction of using extra space.

You could also try reversing an integer. However, if you have solved the problem "Reverse Integer", you know that the reversed integer might overflow. How would you handle such case?

There is a more generic way of solving this problem.

------------------------------------------------------------

9、回文数字

判断一个整数是不是回文数字,不能使用额外的空间。

负数不是回文,如果您正在考虑将整数转换为字符串,请注意使用额外空间的限制,换一句话来说就是不准转化为字符串,因为使用了额外的空间,你也可以尝试反转一个整数。 但是,如果已解决“Reverse Integer”问题,则知道反转的整数可能会溢出。 你将如何处理这种情况?这个问题有一个更为通用的方法。

def isPalindarome(x):if x < 0:return Falsep = xq = 0while p >= 10:q = 10*q + p%10p = p//10print("p",p,"q",q)return q == x//10 and p == x%10
#测试一下
#a = isPalindarome(12521)
#print(a)
#p 1252 q 1
#p 125 q 12
#p 12 q 125
#p 1 q 1252
#True

首先来说明溢出的问题,对于python而言,输入肯定是不会溢出,那反转以后的数字如果溢出了,那么肯定不是回文数字。

代码解释:在while循环中,p是不断地除以10得到商,而q首先是得到最低位数字,然后在之后的每次循环中这个最低位都会乘10,移到最高位,次最低位则会在第二次循环中(p%10)得到,同理移到次最高位,所以这个方法中p和q是相辅相成的。

------------------------------------------

2018.3.21

13. Roman to Integer

Given a roman numeral, convert it to an integer.

Input is guaranteed to be within the range from 1 to 3999.

13、罗马数字转换为整数

讲一个输入为字符串的罗马数字转换为整数

输入确保在1~3999的范围

def romanToInt(s):""":type s: str:rtype: int"""d = {"I":1,"V":5,"X":10,"L":50,"C":100,"D":500,"M":1000}n = len(s)x = 0i=0while i<n:if i>0 and d[s[i]]>d[s[i-1]]:x += d[s[i]] - 2 * d[s[i - 1]]else:x = x+d[s[i]]i+=1return x
s = "IV"
z = romanToInt(s)
print(z)

可以看到输入s应该是一个字符串,返回的是一个Int型的整数。本题先要理解罗马数字的表示方法

罗马数字是阿拉伯数字传入之前使用的一种数码。罗马数字采用七个罗马字母作数字、即Ⅰ(1)、X(10)、C(100)、M(1000)、V(5)、L(50)、D(500)。记数的方法:

  1. 相同的数字连写,所表示的数等于这些数字相加得到的数,如 Ⅲ=3;

  2. 小的数字在大的数字的右边,所表示的数等于这些数字相加得到的数,如 Ⅷ=8、Ⅻ=12;

  3. 小的数字(限于 Ⅰ、X 和 C)在大的数字的左边,所表示的数等于大数减小数得到的数,如 Ⅳ=4、Ⅸ=9;

  4. 在一个数的上面画一条横线,表示这个数增值 1,000 倍

对于1、2两点就是将表示的罗马数字表示的数字进行相加,小坑的是第三点,只有三种能在大的数字旁边,表示的数为大的数字减去小的数字,代码里没有判断罗马数字的合理性,因为我想输入是合法的,如果需要判断输入的合法性,需要多做几个判断。第四点不用考虑,因为保证输入的范围为1~3999。

解说代码,首先我们定义了一个字典,用来存放其中罗马数字所表示的数字,进入while循环,当发现左边的数字比右边的数字小的时候,需要减两倍的小的数字(因为判断左边数字的时候进行了相加,所以需要减两倍),否则进行相加。

---------------------------------------

14. Longest Common Prefix

Write a function to find the longest common prefix string amongst an array of strings.

14、最长的公共前缀

编写一个函数来查找字符串数组中最长的公共前缀字符串。

解题思路:在字符串数组中找出最小的字符串,根据最小的字符串来逐位判断,两个for循环进行判断,第一个for循环得到最小字符串中的下标和字母,第二个for循环根据上面获得的下标和其它字符串进行相比,如果不同,则返回到当前下标未知的字符串,否则继续判断。

def longestCommonPrefix(strs):""":type strs: List[str]:rtype: str"""if not strs:return ""shortest = min(strs, key=len)print(shortest)for i, ch in enumerate(shortest):for other in strs:if other[i] != ch:return shortest[:i]return shortest

------------------------

2018.3.22

20.Valid Parentheses

Given a string containing just the characters ‘(‘, ‘)’, ‘{‘, ‘}’, ‘[’ and ‘]’, determine if the input string is valid.

The brackets must close in the correct order, “()” and “()[]{}” are all valid but “(]” and “([)]” are not.

20、有效的括号

给一个只含有(),{},[]的字符串,(),()[]{}是合法的,但是(]、([)]是不合法的。

解题思路:这是个有顺序的问题,可以考虑采用栈的形式,先进后出或者说后进先出。

class Solution:def isValid(self, s):""":type s: str:rtype: bool"""pars = []dd = {")":"(","}":"{","]":"["}for c in s:if c in dd and dd[c] == pars[len(pars)-1]:pars.pop()print(pars)else:pars.append(c)print(pars)return len(pars)==0

----------------------------------

21. Merge Two Sorted Lists

Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.

Example:

Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4

两个排序好的链表组合起来,依然是排序好的,即返回的新的链表的值从小到大。

解题思路:新建一个链表,next用两个链表当前位置去比较,谁的小就放谁。当一个链表放完之后,说明另外一个链表剩下的元素都比较大,再放进去就好。

#-*- coding:utf-8 -*-
# Definition for singly-linked list.
class ListNode:def __init__(self, x):self.val = xself.next = Noneclass Solution(object):def mergeTwoLists(self, l1, l2):""":type l1: ListNode:type l2: ListNode:rtype: ListNode"""if not l1 and not l2: returnresult = ListNode(0)l = resultwhile l1 and l2:if l1.val < l2.val:l.next = l1l1 = l1.nextelse:l.next = l2l2 = l2.next# 融合后链表的下一位,当前位置刚刚赋值l = l.next# 把剩余的链表排在后面l.next = l1 or l2# 返回融合后链表从第二个对象开始,第一个对象是自己创建的ListNode(0)return result.nextif __name__ == '__main__':# 创建l1和l2两个链表,注意,排序好的就需要arr1和arr2中数字从小到大arr1 = [1, 2, 3]arr2 = [5, 6, 7]l1 = ListNode(arr1[0])p1 = l1l2 = ListNode(arr2[0])p2 = l2for i in arr1[1:]:p1.next = ListNode(i)p1 = p1.nextfor i in arr2[1:]:p2.next = ListNode(i)p2 = p2.nexts = Solution()# 融合两个链表q = s.mergeTwoLists(l1, l2)

------------------------

2018.3.26

26. Remove Duplicates from Sorted Array

Given a sorted array, remove the duplicates in-place such that each element appear only once and return the new length.

Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.

Example:Given nums = [1,1,2],Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively.
It doesn't matter what you leave beyond the new length.

题目的意思大致是:删除已经排列好的数组中的重复部分,使得数组排序为不重复的正确排序,并且返回正确排序的长度,数组中超过该长度的不管它。

解题思路:

#-*- coding:utf-8 -*-
class Solution(object):def removeDuplicates(self, nums):""":type nums: List[int]:rtype: int"""i = 1j = 1size = len(nums)while j<size:if nums[j] == nums[i-1]:j += 1else:nums[i] = nums[j]j += 1i += 1return min(i,size)if __name__ == '__main__':a = [1,1,2,2,3,4,5,5]S = Solution()b = S.removeDuplicates(a)print(b)print(a)
#输出结果:
#5
#[1, 2, 3, 4, 5, 4, 5, 5]

转载于:https://my.oschina.net/u/3629884/blog/1648145

【Leetcode】刷题的开始相关推荐

  1. LeetCode刷题记录15——21. Merge Two Sorted Lists(easy)

    LeetCode刷题记录15--21. Merge Two Sorted Lists(easy) 目录 LeetCode刷题记录15--21. Merge Two Sorted Lists(easy) ...

  2. LeetCode刷题记录14——257. Binary Tree Paths(easy)

    LeetCode刷题记录14--257. Binary Tree Paths(easy) 目录 前言 题目 语言 思路 源码 后记 前言 数据结构感觉理论简单,实践起来很困难. 题目 给定一个二叉树, ...

  3. LeetCode刷题记录13——705. Design HashSet(easy)

    LeetCode刷题记录13--705. Design HashSet(easy) 目录 LeetCode刷题记录13--705. Design HashSet(easy) 前言 题目 语言 思路 源 ...

  4. LeetCode刷题记录12——232. Implement Queue using Stacks(easy)

    LeetCode刷题记录12--232. Implement Queue using Stacks(easy) 目录 LeetCode刷题记录12--232. Implement Queue usin ...

  5. LeetCode刷题记录11——290. Word Pattern(easy)

    LeetCode刷题记录11--290. Word Pattern(easy) 目录 LeetCode刷题记录11--290. Word Pattern(easy) 题目 语言 思路 源码 后记 题目 ...

  6. LeetCode刷题记录10——434. Number of Segments in a String(easy)

    LeetCode刷题记录10--434. Number of Segments in a String(easy) 目录 LeetCode刷题记录9--434. Number of Segments ...

  7. LeetCode刷题记录9——58. Length of Last Word(easy)

    LeetCode刷题记录9--58. Length of Last Word(easy) 目录 LeetCode刷题记录9--58. Length of Last Word(easy) 题目 语言 思 ...

  8. LeetCode刷题记录8——605. Can Place Flowers(easy)

    LeetCode刷题记录8--605. Can Place Flowers(easy) 目录 LeetCode刷题记录8--605. Can Place Flowers(easy) 题目 语言 思路 ...

  9. LeetCode刷题记录7——824. Goat Latin(easy)

    LeetCode刷题记录7--824. Goat Latin(easy) 目录 LeetCode刷题记录7--824. Goat Latin(easy) 题目 语言 思路 后记 题目 题目需要将一个输 ...

  10. LeetCode刷题记录6——696. Count Binary Substrings(easy)

    LeetCode刷题记录6--696. Count Binary Substrings(easy) 目录 LeetCode刷题记录6--696. Count Binary Substrings(eas ...

最新文章

  1. AI+视频分析:实时监测无处不在的安全风险
  2. es6+最佳入门实践(10)
  3. 1114 Family Property (25 分)【难度: 中/ 知识点: 并查集】
  4. liferay jsp如何取PorletSession的值
  5. 使用Mockito和BeanPostProcessors在Spring注入测试双打
  6. android 3.0单元测试,Android Studio 3.0 gradle 3.0.0-beta2打破了Kotlin单元测试覆盖率?
  7. Java 并发(入门梳理)
  8. cocos2d-JS (四)如何学习
  9. SUV 个人收藏汽车
  10. nutch 1.5 solr 4.0 warmup
  11. Java EE组件技术
  12. Finalize/Dispose资源清理模式
  13. Java的强、软、弱、虚四种引用类型
  14. 贝叶斯网络和马尔科夫的冷知识
  15. b. c 语言中有调用关系的所有函数都必须放在同一源程序文件中.,第六章函数-选择题...
  16. ArcGIS 线简化算法的使用及两种方法的比较
  17. 计算机毕业设计Javahtml5健身房信息管理系统(源码+系统+mysql数据库+lw文档)
  18. 详述数据中心内部通风的几种形态
  19. python3模拟键盘输入_python 模拟键盘输入
  20. C#控件的创建、属性设置及事件注册

热门文章

  1. Sql Server中Select @Value和Select Value的区别
  2. hadoop集群配置与启动
  3. 利用PermutationImportance挑选变量
  4. Microsoft Visual Studio 宏脚本添加注释模板
  5. Tp5缓存Cache
  6. React Native知识
  7. 整合初步---------SSH(注解版)
  8. Win7如何改变用户文件夹位置
  9. magento中调用图片的方法
  10. Android下的动画