本文不断更新中node
----------------------------------------python
2018.3.20数组
9. Palindrome Numberapp
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.this
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?spa
There is a more generic way of solving this problem.rest
------------------------------------------------------------code
九、回文数字
判断一个整数是否是回文数字,不能使用额外的空间。
负数不是回文,若是您正在考虑将整数转换为字符串,请注意使用额外空间的限制,换一句话来讲就是不许转化为字符串,由于使用了额外的空间,你也能够尝试反转一个整数。 可是,若是已解决“Reverse Integer”问题,则知道反转的整数可能会溢出。 你将如何处理这种状况?这个问题有一个更为通用的方法。
def isPalindarome(x): if x < 0: return False p = x q = 0 while p >= 10: q = 10*q + p%10 p = p//10 print("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.
1三、罗马数字转换为整数
讲一个输入为字符串的罗马数字转换为整数
输入确保在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 = 0 i=0 while 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+=1 return x s = "IV" z = romanToInt(s) print(z)
能够看到输入s应该是一个字符串,返回的是一个Int型的整数。本题先要理解罗马数字的表示方法
罗马数字是阿拉伯数字传入以前使用的一种数码。罗马数字采用七个罗马字母做数字、即Ⅰ(1)、X(10)、C(100)、M(1000)、V(5)、L(50)、D(500)。记数的方法:
相同的数字连写,所表示的数等于这些数字相加获得的数,如 Ⅲ=3;
小的数字在大的数字的右边,所表示的数等于这些数字相加获得的数,如 Ⅷ=八、Ⅻ=12;
小的数字(限于 Ⅰ、X 和 C)在大的数字的左边,所表示的数等于大数减少数获得的数,如 Ⅳ=四、Ⅸ=9;
在一个数的上面画一条横线,表示这个数增值 1,000 倍
对于一、2两点就是将表示的罗马数字表示的数字进行相加,小坑的是第三点,只有三种能在大的数字旁边,表示的数为大的数字减去小的数字,代码里没有判断罗马数字的合理性,由于我想输入是合法的,若是须要判断输入的合法性,须要多作几个判断。第四点不用考虑,由于保证输入的范围为1~3999。
解说代码,首先咱们定义了一个字典,用来存放其中罗马数字所表示的数字,进入while循环,当发现左边的数字比右边的数字小的时候,须要减两倍的小的数字(由于判断左边数字的时候进行了相加,因此须要减两倍),不然进行相加。
---------------------------------------
14. Longest Common Prefix
Write a function to find the longest common prefix string amongst an array of strings.
1四、最长的公共前缀
编写一个函数来查找字符串数组中最长的公共前缀字符串。
解题思路:在字符串数组中找出最小的字符串,根据最小的字符串来逐位判断,两个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 = x self.next = None class Solution(object): def mergeTwoLists(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ if not l1 and not l2: return result = ListNode(0) l = result while l1 and l2: if l1.val < l2.val: l.next = l1 l1 = l1.next else: l.next = l2 l2 = l2.next # 融合后链表的下一位,当前位置刚刚赋值 l = l.next # 把剩余的链表排在后面 l.next = l1 or l2 # 返回融合后链表从第二个对象开始,第一个对象是本身建立的ListNode(0) return result.next if __name__ == '__main__': # 建立l1和l2两个链表,注意,排序好的就须要arr1和arr2中数字从小到大 arr1 = [1, 2, 3] arr2 = [5, 6, 7] l1 = ListNode(arr1[0]) p1 = l1 l2 = ListNode(arr2[0]) p2 = l2 for i in arr1[1:]: p1.next = ListNode(i) p1 = p1.next for i in arr2[1:]: p2.next = ListNode(i) p2 = p2.next s = 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 = 1 j = 1 size = len(nums) while j<size: if nums[j] == nums[i-1]: j += 1 else: nums[i] = nums[j] j += 1 i += 1 return 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]