本文不斷更新中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]